text:
Q: Unable to update due to less space on boot I have some old linux images taking up space in /boot
$ dpkg -l | grep linux-image
rc  linux-image-5.4.0-70-generic               5.4.0-70.78~18.04.1                              amd64        Signed kernel image generic
rc  linux-image-5.4.0-71-generic               5.4.0-71.79~18.04.1                              amd64        Signed kernel image generic
ii  linux-image-5.4.0-72-generic               5.4.0-72.80~18.04.1                              amd64        Signed kernel image generic
ii  linux-image-5.4.0-73-generic               5.4.0-73.82~18.04.1                              amd64        Signed kernel image generic
ii  linux-image-5.4.0-74-generic               5.4.0-74.83~18.04.1                              amd64        Signed kernel image generic
ii  linux-image-5.4.0-77-generic               5.4.0-77.86~18.04.1                              amd64        Signed kernel image generic
ii  linux-image-5.4.0-80-generic               5.4.0-80.90~18.04.1                              amd64        Signed kernel image generic
ii  linux-image-5.4.0-81-generic               5.4.0-81.91~18.04.1                              amd64        Signed kernel image generic
ii  linux-image-5.4.0-84-generic               5.4.0-84.94~18.04.1                              amd64        Signed kernel image generic
ii  linux-image-5.4.0-86-generic               5.4.0-86.97~18.04.1                              amd64        Signed kernel image generic
iF  linux-image-5.4.0-87-generic               5.4.0-87.98~18.04.1                              amd64        Signed kernel image generic
iF  linux-image-5.4.0-89-generic               5.4.0-89.100~18.04.1                             amd64        Signed kernel image generic
iU  linux-image-generic-hwe-18.04              5.4.0.90.101~18.04.80                            amd64        Generic Linux kernel image

And I am using  5.4.0-86-generic
 $ uname -r
5.4.0-86-generic

And I tried clearing the old linux images using sudo apt-get purge linux-image-5.4.0-{70,71,72,73,74,77,80}-generic
then I faced error:
E: Unmet dependencies. Try 'apt --fix-broken install' with no packages (or specify a solution).

Then tried  sudo apt --fix-broken install , but faced the error:
dpkg: error processing archive /var/cache/apt/archives/linux-image-5.4.0-90-generic_5.4.0-90.101~18.04.1_amd64.deb (--unpack):
 cannot copy extracted data for './boot/vmlinuz-5.4.0-90-generic' to '/boot/vmlinuz-5.4.0-90-generic.dpkg-new': failed to write (No space left on device)

How can I clear space on /boot.

A: That's a case where using a lower level tool can help instead of causing problems. Usually today it's not a good idea to use dpkg directly, but in this case this will help for the same reason: dpkg won't check as much as apt.
You know you won't use earlier kernel versions installed so you can remove them directly. Assuming a bash shell remove all earlier:
dpkg --purge linux-image-5.4.0-{70,71,72,73,74,77,80,81,84}-generic

Then still have apt fix what's broken. As there's now space available, it should succeed in creating one or more initramfs files to finish the package(s) installation.
apt --fix-broken install

Now check again what's left to do:
dpkg -l 'linux-image-5.4.*generic' 'linux-image-generic*'

If there are still package in bad state (the 2nd column letter is in upper-case, as described in dpkg's output: Err: uppercase=bad), which should probably not happen if /boot was in a separate partition, reinstall them by using --fix-broken and providing a solution. Eg if all last three are still broken:
apt-get --fix-broken reinstall linux-image-5.4.0-87-generic linux-image-5.4.0-89-generic linux-image-generic-hwe-18.04

(and then probably get rid of linux-image-5.4.0-87-generic).

Actually using only apt or apt-get should be doable too but the provided solution must be complete and one must hope deinstallation happens first to free disk space. Probably this would also work (notice the minus sign at the end of the package names from bash expansion, telling apt to deinstall instead of reinstall):
apt-get --fix-broken --purge reinstall linux-image-5.4.0-{70,71,72,73,74,77,80,81,84}-generic- linux-image-5.4.0-87-generic linux-image-5.4.0-89-generic linux-image-generic-hwe-18.04


text:
Q: Azure http trigger functions throwing an error over imported modules from other folder We are building an http trigger using Azure functions.
import logging

import azure.functions as func

def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')
    name = req.params.get('name')
    if not name:
        try:
            req_body = req.get_json()
        except ValueError:
            pass
        else:
            name = req_body.get('name')

    if name:
        return func.HttpResponse(f"Hello, {name}. This HTTP triggered function executed successfully.")
    else:
        return func.HttpResponse(
             "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response.",
             status_code=200
        )

From the online platform, we were able to trigger it by adding a parameter and print it on the screen.
Once we try to import files from src folder which at the same level of HttpTrigger1,
import src.main

We have the following error:

Error in load_function. Sys Path:
['C:\Users\AliMehdy\AppData\Roaming\npm\node_modules\azure-functions-core-tools\bin\workers\python\3.10\WINDOWS\X64',

And it points out to main.py where we have already loaded a library called load_toml. Also over each import in main.py from src folder.

So it's throwing the same error over each module.
We did check the documentations and specifically that part:

When you're using absolute import syntax, the shared_code/ folder
needs to contain an init.py file to mark it as a Python package.

Still, we didn't know what to do. Any idea how to import other modules into Azure http trigger function?

A: In One of my previous workarounds, I have created a Python File in the src like folder which is at the same level of HttpTrigger Function Folder level in the Azure Functions Python Project.
from calcfunction import  calc

This is the absolute path I have used in that Http Trigger Function:

Absolute paths are good to use for the above scenarios such as importing modules as a python package in other files.
Refer to this similar scenario on SO #58318794 provided by the user @HassanAbbas.

redpajama_set_name: RedPajamaStackExchange


text:
Q: LINQ equivalent of string.Join that is usable in LINQ to Entities I have a metadata class with some custom properties for easier data access. One problem that I have run across though, is that when I try to use this property in LINQ statements I get this error.
The specified type member 'CrewCodesStr' is not supported in LINQ to Entities.

I know why I get it, I'm wondering if there is another way to do this to allow the property to be used in LINQ statements.
Here is the property:
public string CrewCodesStr
{
    get { return string.Join(", ", CrewCodesList); }
}

Here is an example query that it fails on.
query = query.Where(wo => searchCriteria.crewCode.Contains(wo.CrewCodesStr));

A: You can do a string.Join after you've selected the info you need from your database. If you do a ToList(), this will enumerate the data you need from the database. Then you can do whatever C# you want, as it will run in memory after the ToList()
var result = MyObjects.Select(x => new
{
    ID = x.ID,
    CrewCodes = x.CrewCodes
})
.AsEnumerable()//enumerate the queryable
.Select(x => new
{
    ID = x.ID,
    String = string.Join(",",x.CrewCodes)
});


text:
Q: How to automatically create BibTex citations for R packages in knitr file? I am not sure whether this an R, LaTeX, or BibTex problem.
I am trying to automatically generate a .bib file containing citations for R packages and then list them at the end. I am able to generate the BibTex file and I don't see anything wrong with the BibTex file, but the entries don't appear when I compile the PDF.
I'm not sure if R is not producing a BibTex file correctly, if some LaTeX syntax is wrong, or if the BibTex file needs to be pre-compiled or whatever. I noticed that \bibliography{NOT A REAL FILENAME} will produce a References section without complaining, but I don't think that is the problem.
Minimal working example:
\documentclass[10pt]{amsart}
\usepackage[margin=1in, headheight=20pt, footskip=20pt]{geometry}

\begin{document}

<<label='Create References'>>=
require(knitr) # Needed for write_bib()

# Load some packages to the session:
require(xtable)
require(ggplot2)

# Select packages to cite:
citPkgs <- names(sessionInfo()$otherPkgs)
# Write the bibtex file:
write_bib(citPkgs, file="R-Pckgs.bib")
@

\nocite{*}
\bibliographystyle{plain}
\bibliography{R-Pckgs.bib}

\end{document}

Any help or suggestions would be appreciated.

A: Just replace \bibliography{R-Pckgs.bib} with \bibliography{R-Pckgs}, and it should work fine.
On Windows 7, with an up-to-date MikTeX installation and current R and R packages, the following worked:

*

*Put your reproducible example in a file named "eg.Rnw" and edit to remove the extraneous ".bib"

*Launch R and navigate to the directory in which "eg.Rnw" is located.

*Do library(knitr); knit2pdf("eg.Rnw")
Note: There are obviously many workflows for going from *.Rnw to *.pdf, but if you want to use knit2pdf() (at least), make sure that you run it from the directory containing the *.Rnw to be processed.

A: Add a \nocite{dummycite} to your document - to create a citation so that the bibliography is printed.
Note that this is obsolete if you already have other citation in your document.


text:
Q: jwplayer - change controls look when caption is on i'm building my own jwplayer skin (jwplayer 6) using xml file and i changed the look of the controls bar.
when the caption is on i want the controls bar to look different.
Is that possible?
I found this:
    events: {
            onCaptionsChange: function(event) {
             }
   }

and i think i can add a class to the control bar and work with it with css but it doesn't feel right.


text:
Q: Error: src/app/components/button/button.component.ts:11:27 - error TS1005: '(' expected I'm new to Angular and I'm following a tutorial to get started and I'm getting this error in line 11, even if '(' is present
Error: src/app/components/button/button.component.ts:11:27 - error TS1005: '(' expected.
this is the code of button.component.ts
 import { Component, OnInit, Input, Output, EventEmitter} from '@angular/core';

@Component({
  selector: 'app-button',
  templateUrl: './button.component.html',
  styleUrls: ['./button.component.css']
})
export class ButtonComponent implements OnInit {
  @Input() color: string;
  @Input() text: string;
  @Output() btnEvetn: new EventEmitter(); //line 11

  constructor() { }

  ngOnInit(): void {}

  onClick()
  {
    console.log("Added");
  }

}

also, I'm getting those other errors, all of them on line 11
Error: src/app/components/button/button.component.ts:11:27 - error TS2314: Generic type 'EventEmitter' requires 1 type argument(s).
Error: src/app/components/button/button.component.ts:11:39 - error TS1441: Cannot start a function call in a type annotation.
Error: src/app/components/button/button.component.ts:11:40 - error TS1068: Unexpected token. A constructor, method, accessor, or property was expected.

A: @Output() btnEvetn: EventEmitter<void> = new EventEmitter();


text:
Q: Construct Variable Name at runtime I'm new to AS3 and i need a bit of help.
I have this code to play different audio files and dynamically loop them:
var mIntroLoop = 12495;
var mBattleLoop = 29000;
var currentPlaying;

function playMusic(x):void
{
     musicChannel = x.play();
     currentPlaying = x;
}

function loopSound(m:Object):Function {
  return function(e:Event):void {
         musicChannel = m.play(m.toString() + "Loop");
     musicChannel.addEventListener(Event.SOUND_COMPLETE, loopSound(currentPlaying));
  }
}

playMusic(mIntro);
musicChannel.addEventListener(Event.SOUND_COMPLETE, loopSound(currentPlaying));

As you can see on top of the code i have two variables, mIntroLoop and mBattleLoop.
I need help with this line:
musicChannel = m.play(m.toString() + "Loop");

This is not working of course, it is there just so you know what i'm trying to do.
Into that line, m.play() need to have as argument the returned value of either mIntroLoop or mBattleLoop, depending on what i'm currently playing.

A: I see you solved it yourself, but I think you should look at this anyway.
Because all AS3 classes extend Object class, you can do something like this:
musicChannel = m.play( this[m.toString() + "Loop"] );

Although I don't suggest using this method, as it gets really hard to read when you come back to your code. Otherwise I think it's a clean solution.


text:
Q: How to set text to show currency on tooltip (using plot_ly NOT ggplotly)? As far as I could investigate a need to set the "text" argument when generating the plotly object, and then call this "text" argument as the tooltip.
data:
ha <- structure(list(periodo = structure(c(2L, 2L, 2L, 2L, 2L, 2L), .Label = c("2017",
"2016"), class = c("ordered", "factor")), ecommerce = structure(c(2L,
2L, 2L, 2L, 2L, 2L), .Label = c("falabella", "ripley", "linio"
), class = c("ordered", "factor")), marca = c("samsung", "samsung",
"lg", "lg", "samsung", "lg"), producto = c("samsung tv led hd 32'' 32j4000",
"samsung smart tv led fhd 48\"\" 3d 48j6400", "lg smart tv led 43'' full hd 43lh5700",
"lg smart tv led 49'' full hd 49lh5700", "samsung smart tv 50ju6500 led uhd 50\"\" - negro",
"lg smart tv led 49\"\" ultra hd tv 49uh6500"), precio.antes = c(999,
2799, 1649, 1999, 3699, 2799), precio.actual = c(799, 1999, 1249,
1699, 2399, 2199), pulgadas = c(32, 48, 43, 49, 50, 49), rango = c("S/.500 -\r\n S/.1500",
"S/.1500 -\r\n S/.2500", "S/.500 -\r\n S/.1500", "S/.1500 -\r\n S/.2500",
"S/.1500 -\r\n S/.2500", "S/.1500 -\r\n S/.2500"), descuento = c(-0.2002002002002,
-0.285816362986781, -0.242571255306246, -0.150075037518759, -0.351446336847797,
-0.214362272240086)), row.names = c(NA, 6L), class = "data.frame")

In ggplotly the text argument is placed inside the aes() function.
When using plot_ly I'm placing it inside here:
p <- plot_ly(ha, x = ~periodo, y = ~precio.actual, color = ~ecommerce,colors = c("#BED800", "#802D69", "#FF5500"), text = sprintf("S/ %s", comma(~precio.actual)), textinfo= "text", hoverinfo = "text") %>%
  add_boxplot() %>%
  layout(boxmode = "group") %>%
  config(displayModeBar = FALSE)

p

The code above has no effect on formatting the tooltip.
Shows the tooltip but without the currency formatting needed.
Instead of 2399, it should be S/ 2,399, for example.

A: You can format the y variable in layout by passing a list with hoverformat, which takes a formatting string like sprintf.
plot_ly(ha, x = ~periodo, y = ~precio.actual, color = ~ecommerce,
        colors = c("#BED800", "#802D69", "#FF5500")) %>%
    add_boxplot() %>%
    layout(yaxis = list(
        hoverformat = '$,.2f'
    )) %>%
    config(displayModeBar = FALSE)

If you want to get fancier, you can use hovertemplate. There are lots of examples here: https://plot.ly/r/hover-text-and-formatting/


text:
Q: auth.getInstance not working properly I like a form in where I can update the user data, forget all the logic behind that, I just want to write something on the inputText and save it in firebase. The thing is that I get an error that I don't know the cause. I did a lot of logs and it never enters the if statement in where I check if the user exist.
Code
public class UserSettings extends AppCompatActivity {

    FirebaseDatabase database;
    private FirebaseAuth auth;
    EditText usernameTxt;
    EditText ageTxt;
    String userId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_settings);
        usernameTxt = (EditText)findViewById(R.id.username);
        ageTxt = (EditText)findViewById(R.id.age);
        auth = FirebaseAuth.getInstance();
    }

    public void user(View view){
        String username = usernameTxt.getText().toString();
        int age = Integer.parseInt(ageTxt.getText().toString());
        Log.d("task21",auth.getCurrentUser().toString());

        if (auth.getCurrentUser() == null) {
            Log.d("task","fail2");
        }
        else{
            Log.d("task","fail3");
            userId = auth.getCurrentUser().getUid();
        }
        Log.d("task","fail4");

        DatabaseReference myRef = database.getReference();
        myRef.child("Users").child(userId).child("username").setValue(username);
    }
}

StackTrace
04-12 08:11:30.551 19662-19662/com.android.email E/ActivityThread: Service com.android.email.service.EmailBroadcastProcessorService has leaked ServiceConnection com.android.emailcommon.service.ServiceProxy$ProxyConnection@1ae9859a that was originally bound here
                                                                   android.app.ServiceConnectionLeaked: Service com.android.email.service.EmailBroadcastProcessorService has leaked ServiceConnection com.android.emailcommon.service.ServiceProxy$ProxyConnection@1ae9859a that was originally bound here
                                                                       at android.app.LoadedApk$ServiceDispatcher.<init>(LoadedApk.java:1077)
                                                                       at android.app.LoadedApk.getServiceDispatcher(LoadedApk.java:971)
                                                                       at android.app.ContextImpl.bindServiceCommon(ContextImpl.java:1774)
                                                                       at android.app.ContextImpl.bindService(ContextImpl.java:1757)
                                                                       at android.content.ContextWrapper.bindService(ContextWrapper.java:539)
                                                                       at com.android.emailcommon.service.ServiceProxy.setTask(ServiceProxy.java:181)
                                                                       at com.android.emailcommon.service.ServiceProxy.test(ServiceProxy.java:224)
                                                                       at com.android.email.service.EmailServiceUtils.isServiceAvailable(EmailServiceUtils.java:160)
                                                                       at com.android.email.provider.AccountReconciler.reconcileAccountsInternal(AccountReconciler.java:171)
                                                                       at com.android.email.provider.AccountReconciler.reconcileAccounts(AccountReconciler.java:115)
                                                                       at com.android.email.service.EmailBroadcastProcessorService.reconcileAndStartServices(EmailBroadcastProcessorService.java:305)
                                                                       at com.android.email.service.EmailBroadcastProcessorService.onBootCompleted(EmailBroadcastProcessorService.java:295)
                                                                       at com.android.email.service.EmailBroadcastProcessorService.onHandleIntent(EmailBroadcastProcessorService.java:130)
                                                                       at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:65)
                                                                       at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                       at android.os.Looper.loop(Looper.java:135)
                                                                       at android.os.HandlerThread.run(HandlerThread.java:61)
04-12 08:11:30.562 19662-19717/com.android.email E/EmailServiceProxy: RuntimeException when trying to unbind from service
                                                                      java.lang.IllegalArgumentException: Service not registered: com.android.emailcommon.service.ServiceProxy$ProxyConnection@1ae9859a
                                                                          at android.app.LoadedApk.forgetServiceDispatcher(LoadedApk.java:1029)
                                                                          at android.app.ContextImpl.unbindService(ContextImpl.java:1808)
                                                                          at android.content.ContextWrapper.unbindService(ContextWrapper.java:551)
                                                                          at com.android.emailcommon.service.ServiceProxy$ProxyConnection$1.doInBackground(ServiceProxy.java:124)
                                                                          at com.android.emailcommon.service.ServiceProxy$ProxyConnection$1.doInBackground(ServiceProxy.java:111)
                                                                          at android.os.AsyncTask$2.call(AsyncTask.java:292)
                                                                          at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                                                          at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
                                                                          at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
                                                                          at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
                                                                          at java.lang.Thread.run(Thread.java:818)04-12 08:11:30.551 19662-19662/com.android.email E/ActivityThread: Service com.android.email.service.EmailBroadcastProcessorService has leaked ServiceConnection com.android.emailcommon.service.ServiceProxy$ProxyConnection@1ae9859a that was originally bound here
                                                                   android.app.ServiceConnectionLeaked: Service com.android.email.service.EmailBroadcastProcessorService has leaked ServiceConnection com.android.emailcommon.service.ServiceProxy$ProxyConnection@1ae9859a that was originally bound here
                                                                       at android.app.LoadedApk$ServiceDispatcher.<init>(LoadedApk.java:1077)
                                                                       at android.app.LoadedApk.getServiceDispatcher(LoadedApk.java:971)
                                                                       at android.app.ContextImpl.bindServiceCommon(ContextImpl.java:1774)
                                                                       at android.app.ContextImpl.bindService(ContextImpl.java:1757)
                                                                       at android.content.ContextWrapper.bindService(ContextWrapper.java:539)
                                                                       at com.android.emailcommon.service.ServiceProxy.setTask(ServiceProxy.java:181)
                                                                       at com.android.emailcommon.service.ServiceProxy.test(ServiceProxy.java:224)
                                                                       at com.android.email.service.EmailServiceUtils.isServiceAvailable(EmailServiceUtils.java:160)
                                                                       at com.android.email.provider.AccountReconciler.reconcileAccountsInternal(AccountReconciler.java:171)
                                                                       at com.android.email.provider.AccountReconciler.reconcileAccounts(AccountReconciler.java:115)
                                                                       at com.android.email.service.EmailBroadcastProcessorService.reconcileAndStartServices(EmailBroadcastProcessorService.java:305)
                                                                       at com.android.email.service.EmailBroadcastProcessorService.onBootCompleted(EmailBroadcastProcessorService.java:295)
                                                                       at com.android.email.service.EmailBroadcastProcessorService.onHandleIntent(EmailBroadcastProcessorService.java:130)
                                                                       at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:65)
                                                                       at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                       at android.os.Looper.loop(Looper.java:135)
                                                                       at android.os.HandlerThread.run(HandlerThread.java:61)
04-12 08:11:30.562 19662-19717/com.android.email E/EmailServiceProxy: RuntimeException when trying to unbind from service
                                                                      java.lang.IllegalArgumentException: Service not registered: com.android.emailcommon.service.ServiceProxy$ProxyConnection@1ae9859a
                                                                          at android.app.LoadedApk.forgetServiceDispatcher(LoadedApk.java:1029)
                                                                          at android.app.ContextImpl.unbindService(ContextImpl.java:1808)
                                                                          at android.content.ContextWrapper.unbindService(ContextWrapper.java:551)
                                                                          at com.android.emailcommon.service.ServiceProxy$ProxyConnection$1.doInBackground(ServiceProxy.java:124)
                                                                          at com.android.emailcommon.service.ServiceProxy$ProxyConnection$1.doInBackground(ServiceProxy.java:111)
                                                                          at android.os.AsyncTask$2.call(AsyncTask.java:292)
                                                                          at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                                                          at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
                                                                          at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
                                                                          at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
                                                                          at java.lang.Thread.run(Thread.java:818)

A: First, i thing this error is not belong to your own application some of your email service is leaked.
Second, this should be like this so it want run an exception :
else{
  Log.d("task","fail3");
  userId = auth.getCurrentUser().getUid();
  DatabaseReference myRef = database.getReference();
  myRef.child("Users").child(userId).child("username").setValue(username).addOnCompleteListener(new OnCompleteListener<Void>() {
        @Override
        public void onComplete(@NonNull Task<Void> task) {
            if (task.isSuccessful()){
                Log.d(TAG, "onComplete: DONE");
            }
        }
    });;
 }


text:
Q: How to set file for a silverlight upload button html:
<div id="file">
  <object data="data:application/x-silverlight-2," type="application/x-silverlight-2">
  ...
  </object>
</div>

I've manage to click the silverlight button using following code:
f = Browser.div(:id => "file")
Browser.driver.action.move_to(f.wd).click.perform

However, when the file upload dialog opens, how can I set the file?
I'm using ChromeDriver.

A: According to the documentation, watir-webdriver cannot interact with silverlight objects:

Watir will drive web applications that are served up as HTML pages in a web browser. Watir will not work with ActiveX plugin components, Java Applets, Macromedia Flash, or other plugin applications. To determine whether Watir can be used to automate a part of a web application, right click on the object and see if the View Source menu option is available. If you can view the HTML source, that object can be automated using Watir.


text:
Q: objectdatasource cast gridview datasource back to generic list Environment: asp.net fx3.5
I'm using the objectdatasource for my gridview. At first, I load up my gridview with records from a generic List<Attachments> for my customer. Next I'd like to add/remove items from the gridview without hitting database until after all the add/removes are done. Then the user will hit Save button and then I will persist the items in the gridview.
My question is how do I add/remove items in the gridview while the objectdatasource is wired up to gridview? My guess is somehow cast the gridview rows back to generic list, and add/remove items, and rebind? Is that even possible?

A: I would recommend to save changes to database if you are doing or can do postback on add/remove. As not saving data along change might cause loss of information. You can use ajax call for add/remove to make it more elegant and fast without reloading whole page.
or
If you want to do all add/remove on client side and finally saving to database, you can uses client storage to keep the changes temporarily and finally sending the changes back to server and commit them to database. Article about client storage here but it might not be supported by old browsers
or
You can put change in hidden fields e.g for deleted records you have one hidden field which store deleted record ids, on hidden field with added records with set pattern and update the database on postback using these hidden fields again there is hazard for losing information with this method

A: You can temporarily store in the ViewState. You'll need to have a provider class, i.e. a class which does the basic CRUD operations to the list you are storing in the viewstate.

A: Since you will just be using the grid events to store all this information off for processing, the only thing you would need in your datasource is a select method, that way it won't try to update/Insert the records.  You can do all your event handling on the rowCommand event.
As for what you are trying, I don't think its a good idea.  You will have to track multiple records in your session, or a seperate DB table (but then what would be the point?).


text:
Q: Время существования сессии в CodeIgniter Достался в наследство проект на CI. Механизм сессий реализован через библиотеку Native_session. Появилась задача: убивать сессию после определённого времени бездействия пользователя. Порылся в самой либе, изменение параметра который судя по комментам автора отвечает за время жизни сессии ничего не дало. Добавил свой функционал через дополнительные переменные в $_SESSION, но что то он мне не нравится, предусмотрены ли какие то встроенные способы для реализации данной задачи?
A: config/config.php
$config['sess_expiration']

A: Как гласит этот ресурс время жизни сессии находится здесь:
class Native_session {
    var $session_id_ttl = 360; // session id time to live (TTL) in seconds
    ....

Стало быть надо либо поменять этот параметр, либо при создании объекта подтягивать его из конфига или откуда либо еще


text:
Q: How to export validation rules from salesforce into excel sheet? Is there any way to export all the validation rules in the organisation and export it to excel sheet.

A: Not directly or easily, but it is doable. First, you need to export the metadata which you can do with the Force.com IDE or the Force.com Ant migration tool.  You can get either from the tools part of setup.
Once you get the object files, you will see metadata like this:
<validationRules>
    <fullName>Opt_Out_Required_Reason</fullName>
    <active>true</active>
    <description>Require a reason when op outs are checked</description>
    <errorConditionFormula>AND(OR(DoNotCall = true, HasOptedOutOfEmail = true), ISBLANK( TEXT(Opt_Out_Reason__c )))</errorConditionFormula>
    <errorDisplayField>Opt_Out_Reason__c</errorDisplayField>
    <errorMessage>You must select an opt-out reason if you indicate that this Lead is opting out of email or phone calls.</errorMessage>
</validationRules>

From there, you can format that into an excel table.


text:
Q: Data migration when external Id is not unique on the detail object We are migrating records from one org to another org and I ran into this scenario.
Background:

*

*We have two objects with master detail relation between them and API names are Master__c and Detail__c

*On each object, we have External Id column named External_Id__c to make the data migration easier when moving between environments.

*Here is the simple schema of the data.

*We have two records in Master__c object and 4 records(two records corresponding to each record in master) in Detail__c object.
Data migration:

*

*It is straight forward that first we should move Master__c records and then Detail__c records.

*First, I loaded Master__c records by selecting Upsert Operation in Dataloader and selecting column External_Id__c as external Id and it went fine.
Question:
Can I migrate Detail__c records using Upsert operation given that Detail__c.External_Id__c values are not unique?
I was told by the person who designed that he chose to populate the Detail__c.External_Id__c field to match with its parent record MasterId__r.External_Id__c and mentioned that there are some tools to handle this kind of data when moving between environments. Can someone explain me on how to do this?
Note: I am not looking for crazy vlookup operation.

A: The issue you are having is the CSV for the Detail__c
You have two columns

*

*External_ID__c : This needs to be either null or unique for each detail record

*Master__r.External_Id__c : This should be the external ID of records in Master__c. You will use Data Loader to associate this column to the Master__c.External_Id__c field

When migrating, if Detail__c is never the parent of any other object being migrated, then Detail__c.External_ID__c can be null. But if it will be the parent of some other object, say Foo__c that has a lookup to Detail__c, then these Detail__c will need to have unique External_ID__c
Alternatively, if Detail__c is never the parent of any other object being migrated, just don;t bother to map that column in the Data Loader


text:
Q: ANTLR Parse with Missing Elements How can ANTLR parse missing elements in a list as null (or some other placeholder value)? The following expressions should be distinguishable via the visitor interface.
[1,,2]
[1,2,]
[,1,2]

Here's an example grammar:
grammar Test;

list : '[' elems+=number? (',' elems+=number?)* ']';

number : DIGIT+;
DIGIT: [0-9];

And here's a test program written in Kotlin:
fun main(args: Array<String>) {
    println(doTest("[1,2,]")) // Actual: [1, 2] Expected: [1, 2, null]
    println(doTest("[1,,2]")) // Actual: [1, 2] Expected: [1, null, 2]
    println(doTest("[,1,2]")) // Actual: [1, 2] Expected: [null, 1, 2]
}

fun doTest(input: String): List<Int?> {
    val lexer = TestLexer(CharStreams.fromString(input))
    val tokens = CommonTokenStream(lexer)
    val parser = TestParser(tokens)
    return Visitor.visit(parser.list())
}

object Visitor : TestBaseVisitor<List<Int?>>() {
    override fun visitList(ctx: TestParser.ListContext): List<Int?> =
            ctx.elems.map { s -> s.text.toIntOrNull() }
}

This results in, a list like [1,2] for all three expressions. What changes can I make to be able to distinguish these inputs?

A: Here is how I would do ...
Grammar:
grammar Test;

list : '[' leading_item? item*     ']';

leading_item:
    NUMBER
;

item:
    COMMA | COMMA NUMBER
;

NUMBER:
    '0' | ('1'..'9')('0'..'9')*
;

COMMA:
    ','
;

Extend the base visitor provided by antlr:
public class TestVisitor extends TestBaseVisitor<ArrayList<String>> {
    @Override
    public ArrayList<String> visitList(ListContext ctx) {
        ArrayList<String> ret = new ArrayList<String>();

        if(ctx.leading_item() !=  null) {
            ret.add(ctx.leading_item().NUMBER().getText());
        }

        if(ctx.item() != null) {
            for(ItemContext itemCtx : ctx.item()) {
                if(itemCtx.NUMBER() != null) {
                    ret.add(itemCtx.NUMBER().getText());
                }
                else {
                    ret.add("");
                }
            }
        }

        return ret;
    }
}

Call it
    TestLexer lexer = new TestLexer(charStream);
    TokenStream tokens = new CommonTokenStream(lexer);
    TestParser parser = new TestParser(tokens);
    ParseTree tree = parser.list();

    TestVisitor visitor = new TestVisitor();
    ArrayList<String> list = visitor.visit(tree);

Note:
You have to keep in mind that ANTLR is 'only' providing an easy way to walk trough the grammar. The semantic of list, comma, number is irrelevant for the parser. So when you speak of Missing Elements, it's out of the parser's league.


text:
Q: Designing flyback converter - Switch voltage drop Switch voltage drop is often used in turn ratio calculations, however it is rarely specified in datasheets for converter ICs with built-in FETs. The closest I found is "Rds at Isw". Should I multiply these and use everywhere? Or should I multiply Rds by estimated Iavg or Ipeak? When Vin is low this produces rather huge difference, like 1:5 vs 1:10.
UPDATE:
I think I found an answer on powerelectronics site:
MOSFET conduction loss PCONDmosfet = Imosfeton(avg)^2 x RDSon x D
if PCONDmosfet = Vsw * Imosfeton then Vsw = Iavg x Rds x D
Looks pretty much as I expected, except for that D multiplier.


text:
Q: How to scale a Flink Job that consumes a huge topic The setup:

*

*Flink version 1.12

*Deployment on Yarn

*Programming language: Scala

Flink job:

*

*Two input kafka topics and one output kafka topic

*Input1: is a huge topic between 300K and 500K messages per second. Each message has 600 fields.

*Input2: is a small topic about 20K messages per second once per day. Each message has 22 fields.

*The goal is to enrich Input1 with Input2 and the output is a kafka topic where every message has 100 fields from Input1 and 13 fields from Input2.

*I keep a state from input2 as MapState

*I use RichCoMapFunction to do the mapping

*This is a snippet from the code where I connect both streams:
  stream1.connect(stream2)
     .keyBy(_.getKey1,_.getKey2)
     .map(new RichCoMapFunction)

*I use setAutoWatermarkInterval = 300000

*No checkPoints or savingPoints are currently used
Flink Configurations:

*

*Number of partitions for Input1 = 120

*Number of Partitions for Input2 = 30

*Number of partitions for the output topic = 120

*Total number of Parallelism = 700

*Number of Parallelism for input1 = 120

*Number of Parallelism for input2 = 30

*Join Parallelism:700 (Number of parallelism to connect both stream. This is set as following:
  stream1.connect(stream2)
     .keyBy(_.getKey1,_.getKey2)
     .map(new RichCoMapFunction)
     .setParallelism(700)

*jobManagerMemoryFlinkSize:4096m

*taskManagerMemoryFlinkSize:3072m

*taskManagerMemoryManagedSize:1b

*clusterEvenlySpreadOutSlots:true

*akkaThroughput:1500
Yarn Configurations:

*

*yarnSlots = 4

*yarnjobManagerMemory = 5120m

*yarntaskManagerMemory = 4096m

*Total Number of Task Slots = 700

*Number of Task Managers = 175
Problem:
The latency on the output topic is around 30min which is unacceptable for our use case.
I tried many other Flink configurations related to Memory allocations and vCores but it didn't help.
It would be great if you have any suggestions on how can we scale to reach higher throughput and lower latency.
EDIT1: The RichCoMapFunction code:
class Stream1WithStream2CoMapFunction extends RichCoMapFunction[Input1, Input2, Option[Output]] {

  private var input2State: MapState[Long, Input2] = _

  override def open(parameters: Configuration): Unit = {
    val ttlConfig = StateTtlConfig
      .newBuilder(org.apache.flink.api.common.time.Time.days(3))
      .setUpdateType(StateTtlConfig.UpdateType.OnCreateAndWrite)
      .setStateVisibility(StateTtlConfig.StateVisibility.NeverReturnExpired)
      .build()

    val mapStateDescriptor = new MapStateDescriptor[Long, Input2]("input2State", classOf[Long], classOf[Input2])
    mapStateDescriptor.enableTimeToLive(ttlConfig)
    input2State = getRuntimeContext.getMapState(mapStateDescriptor)
  }

  override def map1(value: Input1): Option[Output] = {
    // Create a new object of type Output (enrich input1 with fields from input2 from the state)
  }

  override def map2(value: Input2): Option[Output] = {
    // Put the value in the input2State
  }
}

A: You could use a profiler (or the flame graphs added to Flink 1.13) to try to diagnose why this is running slowly. The backpressure/busy monitoring added in Flink 1.13 would also be helpful.
But my guess is that tremendous effort is going into serde. If you aren't already doing so, you should eliminate all unnecessary fields from stream1 as early as possible in the pipeline, so that the data that won't be used never has to be serialized. For a first pass, you could do this in a map operator chained to the source (at the same parallelism as the source), but a custom serializer will ultimately yield better performance.
You haven't mentioned the sink, but sinks are often a culprit in these situations. I assume it's Kafka (since you mentioned the output topic), and I'm assume you're not using Kafka transactions (since checkpointing is disabled). But how is the sink configured?
Why have you set the AutoWatermarkInterval to 300000 if your job isn't using watermarks? If you are using watermarks somewhere, this will add up to 5 minutes of latency. If you're not using watermarks, this setting is meaningless.
And why have you set akkaThroughput: 1500? This looks suspicious. I would experiment with resetting this to the default value (15).
Is there any other custom tuning, such as network buffering? I would call into question all non-default configuration settings (though I'm sure some are justified, like memory).
I would also set the parallelism for the whole job to a uniform value, e.g., 700. Fine-tuning individual stages of the pipeline is rarely helpful, and can be harmful.
How have you set maxParallelism? I would set it to something like 2800 or 3500 so that you have at least 4 or 5 key groups per slot.
Could it be that a few instances are doing most of the work? You can examine the metrics on the various sub-tasks of the RichCoMapFunction and look for skew. E.g., look at numRecordsInPerSecond.


text:
Q: how to disable the cors request while redirecting to another url I have an ajax request which does a post to spring controller, where there is response.sendRedirect(externalurl) to external url.
Issue is externalurl does not support cors/jsonp.
But since it is ajax request with cors, "origin" header gets set.
Is there any way to remove the origin header and do response.sendredirect.

A: Try to use response.reset() before sendRedirect.I think it will work in case external url doesn't expects something explicitly.

A: I was able to successfully do it using spring Redirect model and View method.
I stopped using response.sendRedirect.
ModelAndView model = new ModelAndView();
    model.setViewName("redirect:" + authURL);
    return model;


text:
Q: How to populate checkbox from database I have saved value of checkbox in database, now I want to populate these value into checkbox.
Let say, I want to checkbox checked or unchecked according to value in database.
If rowe(0).Item("offer_1").Value.ToString = "Yes" Then
                Offer_1CheckBox.CheckState = CheckState.Checked
            ElseIf rowe(0).Item("offer_1").Value.ToString = "No" Then
                Offer_1CheckBox.CheckState = CheckState.Unchecked
            End If

            If rowe(0).Item("offer_2").Value.ToString = "Yes" Then
                Offer_2CheckBox.CheckState = CheckState.Checked
            ElseIf rowe(0).Item("offer_2").Value.ToString = "No" Then
                Offer_2CheckBox.CheckState = CheckState.Unchecked
            End If

A: If you have not any database exception , you can use below
You dont need any if statements and you should use Checked property
Offer_1CheckBox.Checked = rowe(0).Item("offer_1").Value.ToString = "Yes"
Offer_2CheckBox.Checked = rowe(0).Item("offer_2").Value.ToString = "Yes"


text:
Q: Playing base64 webm audio on Safari I've tried a bunch of things to no avail. Setting the src of an audio element to the following base64 webm dataurl snippet and playing it works in most browsers, but is failing in Safari. Pasting the snippet in the location bar even works in Chrome.
https://gist.github.com/mayorbyrne/99e47f58eefcfe72e84e3e320d136c2c#file-gistfile1-txt
I am able to play a base64 encoded mp3 dataurl, as the following fiddle I found in another response works: https://www.jsfiddle.net/apo299od -- In addition, I've tried replacing the beginning of the snippet data:audio/webm with data:audio/mp3 (works in Chrome, etc), and that moves me further along, but the audio doesn't actually play, it just flashes the audio symbol in the browser for a quick second.
Just wondering if I am spinning my wheels here, or if there is a way to get this snippet playing in an audio element on Safari.

A: Safari on iOS doesn't support the Vorbis / Opus audio codecs in WebM and on desktop only via third-party extensions like the VLC Web Browser plugin. Safari on iOS 11+ / macOS High Sierra+ can play Opus only if it's in a CAF container.

Note: Safari on iOS supports low-complexity AAC audio, MP3 audio, AIF audio, WAVE audio, and baseline profile MPEG-4 video. Safari on the desktop (Mac OS X and Windows) supports all media supported by the installed version of QuickTime, including any installed third-party codecs

source: https://developer.apple.com/library/archive/documentation/AudioVideo/Conceptual/Using_HTML5_Audio_Video/AudioandVideoTagBasics/AudioandVideoTagBasics.html

A: Safari can support Ogg Opus files with WebAssembly decoding.  You can see the demo and code below.  Not as simple as using an <audio> element, but you will get faster, low-latency playback using the Web Audio API:
https://github.com/AnthumChris/fetch-stream-audio


text:
Q: Error Maven Depedency (Missing Artifact -) on springboot project eclipse I just start to try java springboot framework on eclipse and get

all error is from pom.xml, I have never changed pom.xml.

A: *

*for missing artifact u can find solution on following link https://examples.javacodegeeks.com/enterprise-java/maven/maven-resolve-missing-artifact-error-example/

*And for failures to read artifact you can use this command mvn -U clean install .This occurs when your child project is still referring to your parent POM and you have not install from parent pom directory.

A: Follow below to resolve this issue:

*

*Right-click on Project -> Maven -> Update select all projects and update

*Check the maven artifacts are downloaded at repository specified by you in maven settings.xml file

*Check Maven installation in Eclipse -> Preferences -> Maven -> Installation & Settings.xml


text:
Q: Why different styles in same input tag Go to http://jsfiddle.net/j2GZP/1/
<input type="button" value="type = button">
<input type="text" value="type = text" >

I have set a border-radius its working well only on input [type=button] but which styles are Not working input field [type=button] perfectly on Mozilla 21.0
Problems : We can see an another white color in input field edge
screen shot:
Thanks

A: Try
input{
    border-radius: 3px 3px 3px 3px;
    color: #FFFFFF;
    font-weight: 400;
    padding: 6px 20px;
    background:#16A085;
    border:none;
    outline: none;
}

outline:none; removes the white or red border!
Check this fiddle.

A: If I understood the question correctly, you're looking for outline-style:none;. Demo: http://jsfiddle.net/j2GZP/4/


text:
Q: Printing a 2-D array in a function in C I want to initialise and print a 2-D array in two separate functions, but i don't really know if i am doing this correctly.
I wrote 2 functions: int** matrix_initialization(int n, int m)  and  int print_matrix(int n1, int n2, int **a);
In the first function i have to arguments: int n - the number of rows and int m - the number of cols.  In this function i initialise a pointer to the pointer int **matrix = NULL; Then i allocate memory to it, and giving this 2-D array random values.
Is that okay that the type of the int** matrix_initialization(int n, int m) function is int ** ?
The second function is int print_matrix(int n1, int n2, int** a) and there are some problems, the main is that it is not working. I have three arguments int n1 - rows, int n2 - cols, int** a a pointer to the pointer. This function is to print matrix.
Here is my code:
#include <stdio.h>
#include <locale.h>
#include <stdlib.h>
#include <time.h>

int** matrix_initialization(int n, int m)
{
    int** matrix = NULL;
    matrix = (int**)malloc(n * sizeof(n));
    if (matrix != NULL)
    {
        if (matrix != NULL)
        {
            for (int i = 0; i < m; i++)
            {
                *(matrix + i) = (int*)malloc(m * sizeof(m));
            }

            for (int i = 0; i < n; i++)
            {
                for (int j = 0; j < m; j++)
                {
                    matrix[i][j] = rand() % 20 - 5;
                }
            }
        }
    }
    return matrix;
}

int print_matrix(int n1, int n2, int** a)
{
    for (int i = 0; i < n1; i++)
    {
        for (int j = 0; j < n2; j++)
        {
            printf("%d\t", a[i][j]);
        }
        printf("\n");
    }
}

int main()
{
srand(time(NULL));
int N, M, **a;
scanf_s("%d %d", &N, &M);
a = matrix_initialization(N, M);
print_matrix(N, M, a);

}

A: There are many issues with this code.
Major:

*

*You aren't using 2D arrays but arrays of pointers. That doesn't make the slightest sense for this application, you are just making your code more complex, error prone and slow for absolutely nothing gained. See Correctly allocating multi-dimensional arrays.

*matrix = (int**)malloc(n * sizeof(n)); Both of your malloc calls are strange, n is just a size parameter (could as well be size_t) and not necessarily of the same type as the data. Which is a int* in this case, not an int. You should be allocating something like matrix = malloc(n * sizeof(*matrix))

*The first for loop for (int i = 0; i < m; i++) is wrong, should be n.

*You aren't freeing allocated memory.

Minor:

*

*locale.h isn't needed for this program.

*There's no actual need to initialize your pointer matrix to NULL if you are to assign to it on the next line. Also you have multiple redundant checks vs NULL.

**(matrix + i) is never the best way to access an array in C, it's just an obscure way of writing matrix[i]. Don't complicate things just for the heck of it.

*Don't name parameters n and m in one function and then n1 n2 in another function. Don't complicate things just for the heck of it.

*Avoid functions ending with _s unless you have specific reasons why you need to use them. They are non-portable. It's very likely that whoever told you to use it has no idea what they are talking about. Including no idea about the whole "bounds-checking interface" debacle in C11.

*int main() is obsolete style, always use int main (void) (as opposed to C++).

Here is a rewrite with all problems fixed, using 2D arrays instead:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void* matrix_initialization (int n, int m)
{
  int (*matrix)[m] = malloc( sizeof(int[n][m]) );
  if (matrix != NULL)
  {
    for (int i = 0; i < n; i++)
    {
      for (int j = 0; j < m; j++)
      {
          matrix[i][j] = rand() % 20 - 5;
      }
    }
  }
  return matrix;
}

void print_matrix (int n, int m, int a[n][m])
{
  for (int i = 0; i < n; i++)
  {
    for (int j = 0; j < n; j++)
    {
        printf("%d\t", a[i][j]);
    }
    printf("\n");
  }
}

int main (void)
{
  srand(time(NULL));
  int N, M;
  scanf("%d %d", &N, &M);
  int (*a)[M];
  a = matrix_initialization(N, M);
  print_matrix(N, M, a);
  free(a);
}

A: You have two major problems:
The first is
malloc(n * sizeof(n))

which is the same as
malloc(n * sizeof(int))

And that makes no sense when you want to create an array of n pointers to int. On a 64-bit system it's unlikely that sizeof(int) == sizeof(int *).
It should be
malloc(n * sizeof(int*))

Or better yet
malloc(n * sizeof *matrix)

The second problem is your loop where you allocate the int arrays:
for (int i = 0; i < m; i++)

You have just created an array of n elements. Now you iterate over m elements? This will only work if n == m.
The correct loop should of course be
// Iterating over an array of n elements
for (int i = 0; i < n; i++)

You also have the same problem with the malloc call as mentioned above, but this time it just so happens to work because m is an int which is the right type and size.

On another few notes, in C you should not cast the result of malloc.
You never free any of the data you allocate, leading to memory leaks.
And instead of *(matrix + i) use matrix[i].

A: #include <stdio.h>
#include <locale.h>
#include <stdlib.h>
#include <time.h>

int** matrix_initialization(int n, int m)
{
    int** matrix = NULL;
    //matrix = (int**)malloc(n * sizeof(n));
    matrix = (int**)malloc(n * sizeof(int *));

    if (matrix != NULL)
    {
        for (int i = 0; i < n; i++)//here is n,not m
        {
            matrix[i] = (int*)malloc(m * sizeof(int));
        }

        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < m; j++)
            {
                matrix[i][j] = rand() % 20 - 5;
            }
        }
    }

    return matrix;
}

int print_matrix(int n1, int n2, int** a)
{
    for (int i = 0; i < n1; i++)
    {
        for (int j = 0; j < n2; j++)
        {
            printf("%d\t", a[i][j]);
        }
        printf("\n");
    }
    return 0;
}

int main()
{
    srand(time(NULL));
    int N, M, **a,i;
    scanf("%d %d", &N, &M);
    a = matrix_initialization(N, M);
    print_matrix(N, M, a);
    //free all the memory
    for (i = 0; i<N; i++) {
        free(a[i]);
    }
    free(a);
    return 0;
}


text:
Q: Jquery show img title in span I want to show the image title in a span tag. I use this code, but there has nothing showing in the span tag.

...

<?php
$result = mysql_query("SELECT * FROM ...");
$strstr=1;
while ($row = mysql_fetch_array($result))
{
echo '

';
$strstr++;
}
?>

I have checked, the title is not empty in the database. How do I fix it?

A: The problem is that .next() from your  element will be empty - it's the last (only) thing in its surrounding  tag. Try
$this.closest('a').next('span.showtitle').text($this.attr('title'));

A: Try this change:
$('#thumb ul li a img').fadeIn(function() {
        var $this = $(this);
        $this.parent().next('.showtitle').append($this.attr('title'));
    });
});

I added in the .parent().  Yours is grabbing the "next" after the image, but the image is nested inside a link, and the title span follows that link, not the image.


text:
Q: Trigger acts weird when updating rows I have a trigger that updates a row at once. but I'm having some weird problems in doing updates.
When I try to put a more bigger value in commission_pct, the trigger shows another error and not the error that I put into it.
    end if; --The errors are in the next sentences
ELSIF   UPDATING ('COMMISSION_PCT') THEN
    if (:NEW.commission_pct <> 0 and (:OLD.job_id <> 'SA_REP') or (:OLD.job_id <> 'SA_MAN')) then
        raise_application_error(-20002, 'You cannot have commission');
    end if; -- When testing, SQL Developer says here is an error

When testing the updating commission_pct part, it shows me error -20002 when trying to raise the commission_pct to an SA_REP or a SA_MAN Also, when updating commission_pct of an employee who isn't a SA_REP or a SA_MAN, it updates and the trigger does not stop it .
What should I do? I have a syntax error? I am using SQL Developer. Thank you very much.

A: There can be a problem with conditional operators (AND has higher precedence then OR)
if (:NEW.commission_pct <> 0 and (:OLD.job_id <> 'SA_REP') or (:OLD.job_id <> 'SA_MAN')) then

Maybe you wanted this:
if :NEW.commission_pct <> 0 and :OLD.job_id <> 'SA_REP' and :OLD.job_id <> 'SA_MAN' then

Or
if :NEW.commission_pct <> 0 and :OLD.job_id not in ('SA_REP', 'SA_MAN') then


text:
Q: C# 2.0 Execution Time Timer I would like to be able to calculate the amount of time a number of functions take to execute.  I was thinking about using some type of stopwatch class. I can call start/stop before and after each function call, however that seems horribly ugly to me. Is there a way to do this without a stopwatch class? Can something in the Reflections class help with this?
Thanks in advance for you input.

A: I think u must try the PostSharp way http://www.postsharp.org/
Changing the code in the sample for this one:
public class ProfileMethodsAttribute : OnMethodBoundaryAspect
{
  public override void OnEntry( MethodExecutionEventArgs eventArgs)
  { eventArgs.MethodExecutionTag = Stopwatch.StartNew();  }

  public override void OnExit( MethodExecutionEventArgs eventArgs)
  {
     // Here u can get the time
     Console.WriteLine(((Stopwatch)eventArgs.MethodExecutionTag).ElapsedMilliseconds);
  }
}

You can get the time off any method

A: I recommend the sponsor of the performance tag ... Red Gate Ants.  You can get a demo that will run your app and give you performance information for every line and every method that your app hits while it is being profiled.

A: i think you should think about using code profiling... Use an external application like Ants Profiler to profile your code? Ants is from Red Gate and not free but i think that there are a some free/open source apps out there as well.
Some free/open source profilers here...
It's ok to stopwatch a method here and there but trying to do that for every method in your solution would quickly become unwieldy.

A: you could put the stopwatch class into an attribute used to decorate your methods, i.e. the AOP style. check out this

A: There are various timers. System.Timers.Timer would be one such. But as the previous answer suggests, are you sure this is the right solutio to the problem you're actually trying to address?


text:
Q: PSEXEC to get patch list of remote server I am currently trying to get a patch list of a remote server and export the results on to my c:\temp\ folder or on to a network path. I currently have the below code with PSEXEC.
Psexec \\servername  wmic qfe list brief > \\Pathtofolder\General\Test\patches.txt

or if I could get this to export locally on my system
Psexec \\servername  wmic qfe list brief > c:\temp\patches.txt

When I run this with the UNC patch I get the below errors:
Couldn't access servername:
The handle is invalid.
Connecting to servername...
But if I run the command without putting any export path it works absoloutely fine and returns the correct information to my command window.
Psexec \\servername  wmic qfe list brief

Not sure what else I can do.
Also I can not use the powershell get-hotfixid command I need to use this or similiar.
Thanks in advance,
SG

A: for /f "usebackq delims=" %A in ("%userprofile%\desktop\computerlist.txt") Do wmic /node:%A qfe get > "%userprofile%\desktop\%A.txt"

Use %%A in a batch file and %A interactively.
This command builds a list of turned on computers.
for /f "skip=3 delims=\" %%A in ('net view ^| findstr /v /C:"The command completed successfully"') do Echo %%A


text:
Q: Include folder from D: drive on User folder on C: drive On my Windows 7 computer I have 2 drives, C: and D:. On C: drive I have my system installation, and on the D: drive I have my personal data.
I want to sync data between C: and D: on the user folder, so everything will be in the same place, and I could treat D: files path as C: drive.
Is there any way to do that?

A: If you are using NTFS, then you can use a symbolic link (MSDN Article)
For example (in cmd.exe - make sure you quote or escape spaces):
mklink /D "C:\Users\%USERNAME%\My Folder" "D:\My Folder"

Afterwards, you can access D:\My Folder via your home directory (presuming C:\Users\%USERNAME% is your home directory).

A: you can do this without using cmd.exe too.
In Disk Management right click on the partition that you want to be linked.
Click Change Drive Letter and Paths.
Click Add
Then mount in the following empty NTFS folder.


text:
Q: Delete Rows not between Min and Max dates from another column I want to delete records which don't lie between MIN and MAX from another (nullable) column in the table.
Here is the sql fiddle to build schema and sample data:
http://www.sqlfiddle.com/#!3/14686
I have been trying something like this (which ofcourse doesn't work):
DELETE FROM MeterReadings
WHERE ScheduledReadingDate NOT BETWEEN MIN(ActualReadingDate) and MAX(ActualReadingDate)
GROUP BY MeterId

How do I achieve this?

A: You can first select min and max dates and then do the comparison:
with cte as(select *,
                   min(ActualReadingDate) over(partition by meterid) as MinDate,
                   max(ActualReadingDate) over(partition by meterid) as MaxDate
            from meterreadings)
delete from cte
where ScheduledReadingDate not between MinDate and MaxDate

A: Try this
;WITH cte
     AS (SELECT Min(ActualReadingDate) m_ActualReadingDate,
                Max(ActualReadingDate) ma_ActualReadingDate,
                MeterId
         FROM   MeterReadings
         GROUP  BY MeterId)
DELETE M
FROM   MeterReadings M
WHERE  EXISTS (SELECT 1
               FROM   cte c
               WHERE  c.MeterId = m.MeterId
                      AND m.ScheduledReadingDate < m_ActualReadingDate
                      AND m.ScheduledReadingDate > ma_ActualReadingDate)


text:
Q: how to create a web Bookmark with thumbnails android widgets? Could anybody know how to make web bookmark with thumbnails? please give me an idea on how to get the thumbnails or screen shoots of current bookmark websites..
this is the widget that I would like to learn..

A: This is for ICS+ only :
Browser API is being revamped along the lines of Contacts API, now bookmarks are linked to Accounts and also have a folder structure.As far as I know, new Internals have not been exposed via public API calls, and all implementations are likely to be changed in future, and your App might stop working then, if you use internal API. Still, its worth while to know internal workings of android browser provider:
In BrowserProvider2 . Now, thumbnails are in a different table, and have their own  URI. But internally, they are placing data in images table, this also has a URI.
Have a look at structure of new Bookmarks table and Thumbnails table and Images table. Then , see how bookmarks are being inserted :

*

*Legacy calls

*Bookmarks insert

*Extraction of thumbnails etc

*Extracted Images insertion
Also, BrowserContract has these columns defined as ImageColumns these store, thumbnails, favicon, and touch icons etc.
Finally, query() has matches for  IMAGES (no id, url is primary key) and THUMBNAILS (with id).
So, from here you can get whatever images you need using new CONTENT_URI of BrowserContract, append it with URI's of Images,Thumbnails etc and run your queries/inserts .

A: I think for thumbnails you put your link on webView and save your webView under bitmap. Then you save bitmap on SD card and your have your thumbnail.
You can get bookmarks like this :
Cursor mCur  = ActivityChooseBookmark.this.getContentResolver().query(android.provider.Browser.BOOKMARKS_URI,
                        projection, Browser.BookmarkColumns.BOOKMARK, null, null);

Use this to get your bitmap from webView :
public static Bitmap getBitmapFromView(View view) {
        Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(),Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(returnedBitmap);
        Drawable bgDrawable = view.getBackground();
        if (bgDrawable!=null)
            bgDrawable.draw(canvas);
        else
            canvas.drawColor(Color.TRANSPARENT);
        view.draw(canvas);
        return returnedBitmap;
    }

Now just save it on SD and it's done


text:
Q: Is there a better way to structure a C project with cmake? I'm starting a new C project using CMake, so I created a directory structure very similar to the ones I use in Python (my "main" language). Although it compiles correctly, I'm not certain I'm doing it the right way. This is the current structure:
.
├── CMakeLists.txt
├── dist
│   └── # project will be built here, 'cmake ..'
├── extras
│   ├── CMakeLists.txt
│   ├── extra1
│   │   ├── CMakeLists.txt
│   │   ├── extra1.h
│   │   └── extra1.c
│   └── extra2
│       ├── CMakeLists.txt
│       ├── extra2.h
│       └── extra2.c
├── src
│   ├── CMakeLists.txt
│   ├── main.c
│   ├── module1.h
│   ├── module1.c
│   ├── module2.h
│   └── module2.c
└── test
    ├── CMakeLists.txt
    ├── test_module1.c
    └── test_module2.c

Since all files are distributed across multiple directories, I had to find a way to locate the libraries present in extras and the ones I need to test in src. So, these are my CMakeLists':
./CMakeLists.txt
cmake_minimum_required(VERSION 2.8)

project(MyProject)
add_definitions(-Wall -std=c99)

# I don't know really why I need this
set(EXECUTABLE_OUTPUT_PATH ${PROJECT_BINARY_DIR}/dist)

add_subdirectory(src)
add_subdirectory(test)
add_subdirectory(extras)

enable_testing()

add_test(NAME DoTestModule1 COMMAND TestModule1)
add_test(NAME DoTestModule2 COMMAND TestModule2)

./src/CMakeLists.txt
macro(make_library target source)
    add_library(${target} ${source})
    target_include_directories(${target} PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
endmacro(make_library)

make_library(Module1.o module1.c)
make_library(Module2.o module2.c)

./test/CMakeLists.txt
macro(make_test target source library)
    add_executable(${target} ${source})
    target_link_libraries(${target} Libtap.o ${library})
    target_include_directories(${target} PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
endmacro(make_test)

make_test(TestModule1 test_module1.c Module1.o)
make_test(TestModule2 test_module2.c Module2.o)

./extras/CMakeLists.txt
# Hopefully you'll never need to change this file
foreach(subdir ${SUBDIRS})
    add_subdirectory(${subdir})
endforeach()

(Finally) ./extras/libtap/CMakeLists.txt
add_library(Libtap.o tap.c)
target_include_directories(Libtap.o PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})

So, now the question: the reason I'm worried is that this setup will create a 'public' library for every file I'm using, including extra libs (which are not meant to be distributed). If I have 10 libraries in src, 4 dependencies in extras (including libtap, which I'm using to test) and at least the same amount of test files, I'll end up with 24 compiled artifacts.

*

*Is there any better way to expose libraries to linking?

*I'm not compiling "main" yet, what would be the right configuration for that?

*is add_definitions the right way to add flags to the compiler?

*How can I make this structure more DRY?

A:
Is there any better way to expose libraries to linking?

No, this seems fine.
You might however want to reconsider the granularity at which you create static libraries. For example, if all applications except the tests will only ever use Module1 and Module2 in combination, you might want to merge them into a single library target. Sure, the tests will link against parts of the component that they do not use, but that is a small price to pay for the decrease in build complexity.

I'm not compiling "main" yet, what would be the right configuration
  for that?

There's nothing wrong with adding it to the src/CMakeLists.txt as well:
add_executable(my_main main.c)
target_link_libraries(my_main Module1.o Module2.o)

is add_definitions the right way to add flags to the compiler?

It can be used for that purpose, but might not be ideal.
Newer CMake scripts should prefer the target_compile_options command for this purpose. The only disadvantage here is that if you want to reuse the same compile options for all targets in your projects, you also have to do the same target_compile_options call for each of those. See below for tips on how to resolve that.

How can I make this structure more DRY?

First of all, unlike most program code, redundancy is often not that big an issue in build system code. The notable thing to look out for here is stuff that gets in the way of maintainability. Getting back to the common compiler options from before: Should you ever want to change those flags in the future, it is likely that you want to change them for every target. Here it makes sense to centralize the knowledge about the options: Either introduce a function at the top-level that sets the option for a given target, or store the options to a global variable.
In either case you will have to write one line per target to get the option, but it will not generate any maintenance overhead after that. As an added bonus, should you actually need to change the option for only one target in the future, you still have the flexibility to do so.
Still, take care not to overengineer things. A build system should first and foremost get things done.
If the easiest way to set it up means you copy/paste a lot, go for it! If during maintenance later it turns out that you have some real unnecessary redundancies, you can always refactor.
The sooner you accept the fact that your CMake scripts will never be as pretty as your program code, the better ;)
One small nitpick at the end: Avoid giving your target names extensions. That is, instead of
add_library(Libtap.o tap.c)
consider
add_library(Libtap tap.c)
CMake will automatically append the correct file ending depending on the target platform anyway.


text:
Q: In meteor how to verify user password before running a method? I have a user profile page where I let the user edit his details. Before the user save these details, I need to ask for the user's password and verify it. How can I do this? The only method I use password for is the login method.
How can we verify the logged in user's password?


text:
Q: array_multisort not working I have two different arrays
$player_details
Array (
[83] => Array ( [number] => 2
                [name] => Mario Goetze
                [position] => Sturm
                [age] => 37 )
[96] => Array ( [number] => 4
                [name] => Lukas Podolski
                [position] => Torwart
                [age] => 24 )
[66] => Array ( [number] => 1
                [name] => Marco Reuss
                [position] => Langzeitverletzt
                [age] => 24 )
[359] => Array ( [number] => 99
                 [name] => Inge Schmidt
                 [position] => Mittelfeld
                 [age] => 23 )
 )

$array_positions
$array_positions = array("Torwart", "Abwehr", "Mittelfeld", "Sturm", "Spielberechtigte Talente (A-Jugend)", "Langzeitverletzt");

I wanted to sort $player_details after $array_positions to get the right order for my footbal team
array_multisort($player_details["position"],$array_positions);

But that's not working. What can be wrong?

A: you try to sort an array by an individually sort algo. look at the php function usort
http://de2.php.net/manual/de/function.usort.php
usort($player, function($a, $b) use ($array_positions){
    $aPos = $a['position'];
    $aVal = array_search($aPos, $array_positions);
    $bPos = $b['position'];
    $bVal = array_search($bPos, $array_positions);

    if( $aVal == $bVal ) return 0;
    return ($aVal < $bVal) ? -1 : 1;
});


text:
Q: Defining multiple projections inside a file gdb [error 000289 failed to alter spatial reference]? I am importing multiple shapefiles into a filegdb in ArcGIS 10, and using the following code to define the projection of the feature once imported, to the .prj of the original .shp file.
Here is my code:
for spatial in SpatialRefList:
    del gp
    import arcpy as gp
    print 'DEFINING PROJECTION'

    print 'FEATURECLASS = ' + str(featureclass)
    print 'PROJECTION = ' + str(prjfile)
    time.sleep(1)
    try:

        gp.DefineProjection_management(featureclass, prjfile)

    except:
        traceback.print_exc()
        time.sleep(2)

However the code is throwing up error 000289 - failed to alter spatial reference.

A: GDBs are just like a file tree structure. Feature Datasets can only contain feature classes in one spatial reference.
However there is another object called a feature dataset that will allow you to seperate and assign different references per feature dataset.
esri help feature dataset
esri hellp creating feature dataset (code)


text:
Q: Combining one faceted and one unfaceted ggplot2 in a row, ensuring the panels are the same width I am in a situation in which I would like to combine two ggplot2 plots together in a row. For sake of argument, Plot 1 is a single panel and Plot 2 is faceted into two panels. I would like to combine these together into a row of three plots, which can be achieved using cowplot / patchwork.
The key thing is that I would like to ensure each panel is the same width. Using the below code gets close, but the use of rel_widths still means that the actual plotting area of Plot 1 is small (I think due to rel_widths counting axis labels etc. and not the actual plotting area).
Is there a way of doing this simply? Setting the aspect ratio of the ggplot does not work.
The reason I am doing this is for two of the panels to share an axis but one to have its own. ggplot2 itself seemingly doesn't have functionality to do this.
library(tidyverse)

plt1 = iris %>%
  filter(Species == Species[1]) %>%
  ggplot(aes(x = Sepal.Length, y = Petal.Length)) +
  geom_point() +
  facet_wrap(~"setosa")

plt2 = iris %>%
  filter(Species != Species[1]) %>%
  ggplot(aes(x = Sepal.Length, y = Petal.Length)) +
  geom_point() +
  facet_wrap(~Species)

cowplot::plot_grid(plt1, plt2, rel_widths = c(1,2),
                   align = "hv", axis = "l")


text:
Q: Change the number of products per row, depend on screen size Woocommerce I want to change the number of products per row (category page), depend on screen size.
jQuery(window).resize(function(){
   var width = jQuery(window).width();

   if(width >= 1000 && width <= 1200){
     jQuery('.sentry-product').removeClass('columns-4').addClass('columns-3');
     }
   else{
     jQuery('.sentry-product').removeClass('columns-3').addClass('columns-4');
     }
})
.resize();

I'm using this jQuery to change the number of possible columns,
I need to change the number of product as well,
Now I'm hardcoding the number of products
        function storefront_product_columns_wrapper() {
        $columns = storefront_loop_columns();
        echo '<div class="sentry-product columns-' . intval( $columns ) . '">';
    }
}

if ( ! function_exists( 'storefront_loop_columns' ) ) {
    /**
     * Default loop columns on product archives
     *
     * @return integer products per row
     * @since  1.0.0
     */
    function storefront_loop_columns() {
        return apply_filters( 'storefront_loop_columns', 4 ); // 4 products per row
    }
}

I have another idea,
If I can pass the number of product as a parameter from the class name it will fix the issue - return apply_filters( 'storefront_loop_columns', X );
I don't understand if I can do it, Some ideas?

A: This is how to do it with three columns, reducing to two on a viewport of 600px or less;
@media screen and (max-width: 600px) {

.woocommerce.columns-3 ul.products li.product, .woocommerce-page.columns-3 ul.products li.product {
   width: 45%; /* was 30.75% */
}

.woocommerce ul.products.columns-3 li.product, .woocommerce-page ul.products.columns-3 li.product {
  width: 45%; /* for category pages */
}

.woocommerce ul.products li.first, .woocommerce-page ul.products li.first {
  clear: none; /* was both */
}

.woocommerce ul.products li.last, .woocommerce-page ul.products li.last {
  margin-right:3.8%; /* was 0 */
}

Obviously you'll have to adjust for a different number of columns or breakpoint. And I'm about to write another set for 480px so I can have one product per row on phones. This CSS comes after woo commerce's CSS (or use !important)


text:
Q: eventqueue meaning of arrow because I couldn't find anything in google that would explain that, I decided to turn myself to ask you what the arrow in this specific example does, I never saw that expression so I don't really get it what it does.
Site I try to learn from: http://zetcode.com/tutorials/javagamestutorial/basics/
Thanks for helping!~
   public static void main(String[] args) {

        EventQueue.invokeLater(() -> {
            Application ex = new Application();
            ex.setVisible(true);
        });
    }

A: It's part of a lambda expression, which is a shorthand for defining functions. This creates a class with a method that takes no arguments and executes the statement block.
() -> {
    Application ex = new Application();
    ex.setVisible(true);
}


text:
Q: How to not display p:dialog on selecting "Select One" selectitem in PrimeFaces I have a p:selectOneMenu and in that list of values where the first value is "Select One" and other values are actual values fetching from db.
When the user selects other values then a dialog box is displaying and fetching respective values, however, after that if user select "Select One" then also displaying the dialog box. Here, I don't want to display dialog box when user select "Select One" from the dropdown.
Xhtml Code:
<p:selectOneMenu id="drp_modify"
        value="#{BackingBean.Name}" panelStyle="width:180px"
        effect="fade" style="width:180px" filter="true"
        filterMatchMode="startsWith" onchange="PF('dlg_modify').show();"
        title="Add">
        <p:ajax listener="#{BackingBean.onNameChange}"
            update="Name_ID, address" />
        <f:selectItem itemLabel="Select One" itemValue="" noSelectionOption="true" />
        <f:selectItems value="#{BackingBean.nameItemList}" />
    </p:selectOneMenu>

<p:dialog header="Modify" widgetVar="dlg_modify" resizable="false">

//// some code

</p:dialog>

A: You can use JavaScript to check the current value of the combobox.
Instead of onchange="PF('dlg_modify').show();" you can write:
onchange="if(document.getElementById('yourFormId:drp_modify_input').value != '') PF('dlg_modify').show();"

where yourFormId is the ID of your form and the condition is the value given as an itemValue parameter in f:selectItem. In your case it's ''.


text:
Q: Namespace undefined in Internet Explorer only? I am using the Google Closure Library to implement a very big scale project. I have just started working on it, however I'm getting a strange error in IE8. It is the only browser that detects JavaScript errors in the page, and I cannot understand why.
http:://www.niuzly.com/ajax/niuzly.base.js
This is the link to the JS script used. It is using the Google JavaScript Guidelines, so it should be fairly easy to understand everything. Thank you for your time!

A: The linked JavaScript file "niuzly.base.js" does not appear to goog.provide the namespace. Try adding the following line below your copyright notice:
goog.provide('niuzly.base.renderPage');

You should also explicitly goog.require 'goog.dom`:
goog.require('goog.dom');


text:
Q: .Net Core NewtonsoftJson DateTimeZoneHandling setting not working I started porting our .Net Framework WebAPIs to .Net Core 5 at work.  I noticed that dates being returned in the SPA were off and upon further investigation I saw that after the objects were serialized that the dates were being set as UTC.
I've found that I can get it to work at serialization/deserialization by adding the option as an argument, but it seems like this should be able to be done globally instead of each time the serializer runs.
I've tried adding the following in the WebAPI Startup.cs to change how the dates were being returned but it doesn't seem to work in the startup:
services.AddControllers().AddNewtonsoftJson(o => o.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Unspecified);

A: Add this:
services.AddControllers().AddNewtonsoftJson();

JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{

    DateTimeZoneHandling = DateTimeZoneHandling.Unspecified
};

A: I had to convert to UTC format(DateTimeZoneHandling.Utc) and the above ways(DateTimeZoneHandling) did not work for me. Finally below worked:
.AddNewtonsoftJson(opts =>
            {
                opts.SerializerSettings.Converters.Add(new IsoDateTimeConverter
                    {
                        DateTimeStyles = DateTimeStyles.AdjustToUniversal
                    });
            }

I hope this helps to people who are looking to convert date time format to UTC globally.


text:
Q: Is everything in Kotlin an object? I have read this in several places. But don't really understand the meaning. You can read this short documentation on kotlinlang:
"In Kotlin, everything is an object in the sense that we can call member functions and properties on any variable. Some of the types can have a special internal representation - for example, numbers, characters and booleans can be represented as primitive values at runtime - but to the user they look like ordinary classes."
What is a special internal representation? What does it mean, can be represented as primitive values at runtime?
Is it only the possibility to call conversion functions like toInt()? And the Extension Functions?
Elsewhere I have read the following statement:
"For primitive data types from java, kotlin has specialized array types like ByteArray". Does it mean that I can only create an Array in Kotlin with functions like intArrayOf(1, 2, 3) or IntArray(5)?
Another statement that I find confusing from the book Head First Kotlin:
"When you declare a variable using code like:
var x = 5

the value you're assigning to the variable is used to create a new object".
"When an object is assigned to a variable, the object itself doesn't go into the variable. A reference to the object goes into the variable instead:"

But the following code snippet does the same which I get with Java.
fun main() {
    var x = 5
    var y = x
    x = 15
    println("Hello, world!!! $y")
}

The output is 5. But I think it should be 15, because it is an object and a reference to it. Maybe I am a little bit stupid to understand Kotlin.
That is my understanding of variables and references and the administration of memory in programming languages like Java (or Kotlin).

A: lets think they are objects and not primitives
var x = 10

assign reference of 10 to x
var y = x

assign reference of x to y
x = 5

assign reference of 5 to x
so reference of x changed but y keeps reference of 10
in another way
if you can do something like this
x.changeSomeOfMyProperties()

then changes will be applied to x and y but, because they are primitives you cannot do that kind of thing.
primitives are classes in kotlin, so it is difficult to understand how they work,
you can check Primitives.kt

A:
The output is 5. But I think it should be 15

We can walk through what's going on in this sample.
var x = 5

Create an Int object holding the value 5. Create a variable x, and make x point to this new Int object.
var y = x

Create a variable y, and make y point to whatever x is currently pointing to (the Int object).
(Note that it is not the case that x and y are two names for the same pointer. Rather, x and y are totally distinct but both happen to point at the same thing.)
x = 15

Create an Int object holding the value 5. Make the x variable point to this new Int object.
(This is the key point in the flow. When we assign x = 15, we are changing where x points, but we aren't affecting y at all. y still points to the same thing it used to (the Int holding 5)).
println("Hello, world!!! $y")

Display something to the user. To determine what to substitue for $y, follow the pointer and see what it's pointing to. y was only ever assigned a value one time, so it still points to the first thing it ever pointed to (the Int holding 5).

A: To answer your first question, Everything to you the developer is an object or behaves like an object but at runtime for efficiency sake compiles down to primitive type.
for the last one :
x = 5 //and let's say int 5 memory location is A235

so
y = x is synonymous to y = A235

then
x = 15

but y is still pointing to memory location A235 value

A: All primitives are represented as their respective JVM types unless you specifically access them as or force them to be an object.
For sake of showing what I mean, let's use System.identityHashCode(Object) function. Also using Int value > 127 to prevent object caching.
Case 1: primitives
fun main(){
    var x = 128
    var y = x
    println("x: $x, ${System.identityHashCode(x)}")
    println("x: $x, ${System.identityHashCode(x)}")
    println("y: $y, ${System.identityHashCode(y)}")

    x = 200
    println("x: $x, ${System.identityHashCode(x)}")
}

/// output
x: 128, 746292446
x: 128, 1072591677
y: 128, 1523554304
x: 200, 1175962212

What we get here: x is a primitive int and is stored as such. when y = x, that means y is assigned same primitive value as x. There are no Objects allocated yet.
When we use System.identityHashCode(Object) we get different hashes, even when we print x twice in a row. That's because Int wrapper objects are created on the spot where Object representation is needed.
Case 2: object representation
fun main() {
    var x : Any = 128  // this is the only line that changed
    var y = x
    println("x: $x, ${System.identityHashCode(x)}")
    println("x: $x, ${System.identityHashCode(x)}")
    println("y: $y, ${System.identityHashCode(y)}")

    x = 200
    println("x: $x, ${System.identityHashCode(x)}")
}

/// output
x: 128, 746292446
x: 128, 746292446
y: 128, 746292446
x: 200, 1072591677

Here we force x to be represented as an Object by declaring field type as non-primitive. When we assign x to y that object reference is copied and we can see that by identityHashCode returning same hash in all prints.

A: But what is the difference to Java here? I think Java does the same with the primitive Variables like x and y. When we assign y to x in Java and we will change x after that, y has still the old value. Because it is a copy and not a reference.
So the only difference between Kotlin and Java is I can call functions on primitive datatypes and give them properties like with objects?


text:
Q: Pie chart: image exporting cutting off labels I'm using Highcharts 3 pie chart and when I do export to image the generated chart are losing some data labels. How can I solve (workaround) this?
ps: Using highcharts server: export.hightcarts.com
Regards
[update]
Small values are cut off on generated image png file. However is ok in the print preview.
new Highcharts.Chart({
    chart: {
        renderTo: 'chart',
        type: 'pie'
    },
    title: {
        text: 'My Chart title'
    },
    plotOptions: {
        pie: {
            showInLegend: true,
            dataLabels: {
                enabled: true,
                formatter: function() {
                    return '<b>' + this.point.name + '</b>: ' + Math.round(this.point.total * this.point.percentage / 100);
                }
            }
        }
    },
    series: [{
        type: 'pie',
        name: 'Series name',
        data: [
            ["Lorem", 88],
            ["Lorem ipsum", 4],
            ["Praesent nibh nulla", 12],
            ["Lorem ipsum dolor sit amet", 66],
            ["Praesent fringilla suscipit molestie", 30],
            ["Donec at lectus at nulla viverra lobortis", 11],
            ["Class aptent taciti sociosqu ad litora", 87],
            ["Mauris vulputate sem id arcu volutpat fermentum", 149],
            ["Vestibulum faucibus lectus", 113],
            ["Pellentesque habitant morbi tristique", 7],
            ["Etiam lacinia mi suscipit", 92],
            ["Proin semper risus in lacus semper", 9],
            ["Fusce id faucibus massa", 99],
            ["Suspendisse", 4],
            ["Quisque quis lectus et turpis laoreet", 101]
        ]
    }],
    exporting: {
        enabled: true
    }
});

jsFiddle: http://jsfiddle.net/6afyH/1/

A: It is because Highcharts does not detect the width of the container.
You can fix that by adding the option sourceWidth in the exporting option :
exporting: {
    enabled: true,
    sourceWidth: 900
}

It seems that sourceWidth take the initial width so if the chart is a little bit truncated at the page loading, it will be the same at the exporting unless if you specified it in the options.
I updated the jsFiddle to give you an example of this working : http://jsfiddle.net/6afyH/2/


text:
Q: Create Batch file to run mstest for coded ui test automation Can someone help me out in creating Batch file to run the coded ui test using mstest?
I am currently running the coded ui test in the command prompt by running as administrator by using below lines in command prompt:
cd\
cd C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE

C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE>MSTest.exe /testcontainer:D:\Working\LOPS_Testing\LOPS6Automation\bin\LOPS6Automation.dll /test:Light_Oil_Price_System.Scripts.PricingScreen_Script.PricingScreenFunctionality

This works correctly.
But now I want to use the same in a batch file. Can some one help me out to create a batch file by using the above code?

A: Wrap paths with spaces between quotes.
I also used cd /D, that changes drive if necessary (for example if you were on drive D: you would need to change to C: before cd commands. With /D option this is done automatically)
Also, since you are already on the Common7\IDE folder, you don't need to write again the directory, you could just call MSTest.exe:
cd /D "C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE"

MSTest.exe /testcontainer:D:\Working\LOPS_Testing\LOPS6Automation\bin\LOPS6Automation.dll /test:Light_Oil_Price_System.Scripts.PricingScreen_Script.PricingScreenFunctionality


text:
Q: Haproxy not bind to frontend on Ubuntu Server 18.04 How to solve Haproxy not working on ubuntu server, did I missing something, need a guide here.
Below I do not have a problem on my local macbook docker compose,
stm-haproxy    | listen stats
lstm-haproxy    |   bind :1936
lstm-haproxy    |   mode http
lstm-haproxy    |   stats enable
lstm-haproxy    |   timeout connect 10s
lstm-haproxy    |   timeout client 1m
lstm-haproxy    |   timeout server 1m
lstm-haproxy    |   stats hide-version
lstm-haproxy    |   stats realm Haproxy\ Statistics
lstm-haproxy    |   stats uri /
lstm-haproxy    |   stats auth stats:stats
lstm-haproxy    | frontend default_port_80
lstm-haproxy    |   bind :80
lstm-haproxy    |   reqadd X-Forwarded-Proto:\ http
lstm-haproxy    |   maxconn 4096
lstm-haproxy    |   default_backend default_service
lstm-haproxy    | backend default_service
lstm-haproxy    |   server lstm_lstm_1 lstm_lstm_1:8008 check inter 2000 rise 2 fall 3
lstm-haproxy    |   server lstm_lstm_2 lstm_lstm_2:8008 check inter 2000 rise 2 fall 3
lstm-haproxy    | INFO:haproxy:Config check passed
lstm-haproxy    | INFO:haproxy:Reloading HAProxy
lstm-haproxy    | INFO:haproxy:Restarting HAProxy gracefully
lstm-haproxy    | INFO:haproxy:HAProxy is reloading (new PID: 11)
lstm-haproxy    | INFO:haproxy:===========END===========

But when I push to my staging server, ubuntu server 18.04
lstm-haproxy    | listen stats
lstm-haproxy    |   bind :1936
lstm-haproxy    |   mode http
lstm-haproxy    |   stats enable
lstm-haproxy    |   timeout connect 10s
lstm-haproxy    |   timeout client 1m
lstm-haproxy    |   timeout server 1m
lstm-haproxy    |   stats hide-version
lstm-haproxy    |   stats realm Haproxy\ Statistics
lstm-haproxy    |   stats uri /
lstm-haproxy    |   stats auth stats:stats
lstm-haproxy    | INFO:haproxy:Launching HAProxy
lstm-haproxy    | INFO:haproxy:HAProxy has been launched(PID: 9)

My docker and docker-compose versions on macbook,
Docker version 18.09.1, build 4c52b90
docker-compose version 1.23.2, build 1110ad01

My docker and docker-compose versions on ubuntu server,
Docker version 18.09.1, build 4c52b90
docker-compose version 1.23.1, build b02f1306

This is my docker-compose.yml,
version: '3'

services:
  lstm:
    restart: always
    build:
      context: .
    environment:
      MAX_REQUEST: 100
      NUM_WORKER: 5
      BIND_ADDR: 0.0.0.0:8008
    command: bash monkey-sync.sh
  lstm-haproxy:
    image: dockercloud/haproxy
    links:
      - lstm
    ports:
      - '8008:80'
    container_name: lstm-haproxy
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock

This is my dockerfile,
FROM python:3.6.1 AS base

RUN pip3 install blablabla

WORKDIR /app

COPY . /app

RUN echo

ENV LC_ALL C.UTF-8
ENV LANG C.UTF-8

EXPOSE 8008

Any guides really help me a lot, thanks!

A: Solved! Need to set SERVICE_PORTS: 8008 on lstm environment.


text:
Q: Stop text moving when border change width i am facing a really annoying problem ^^. My left menu text is moving when the border is expanded with jquery. I am trying everything to stop moving the text. but nothing works :/
Any idea ?
CSS for left menu?
.main .left {
    width: 220px;
    margin-right: 20px;
    float: left;
}
.main .box {
    margin-top: 10px;
}
.main .box .bname {
    font-size: 15px;
    background: url(../images/sepa.png) no-repeat left center;
    padding: 5px 0 5px 15px;
}
.main .box ul {
    margin: 10px 0 0 0;
    padding: 0;
    list-style: none;
}
.main .box ul li {
    padding-left: 10px;
    margin-bottom: 1px;
}
.main .box ul li a {
    display: block;
    padding: 3px;
}

.main .box ul li a:hover{}

My jquery for animated border:
jQuery(document).ready(function($) {
    $(".box ul li").hover(function() {
        $(this).animate({borderWidth: 20}, "fast");
    }, function() {
        $(this).animate({borderWidth: 2}, "fast");
        });
});

The problem is when the border animate ( borderWidth: 20 ) it will move text to the right. I want the text fixed on the same place.
my html:

Dokumenty

       {foreach $MENU['USER1'] as $row}

               odkaz}" {widget  rsLista 'MENU',$row->idecko,$MENU_WEB['USER1'],$MENU_SLOZKA['USER1'],$row->nazev}>{$row->nazev}

       {/foreach}

A: You can fix the text by manipulating element padding and making it part of the animation:
CSS
.main .box ul li{padding:18px; margin-bottom: 1px;}

JS
$(".box ul li").hover(function() {
   $(this).animate({borderWidth: 20, padding:2}, "fast");
 }, function() {
   $(this).animate({borderWidth: 2, padding:18}, "fast");
});

see http://jsfiddle.net/6VjCr/


text:
Q: how to add file open password to excel file by VBA i have a VISUAL BASIC code that creates a copy of the EXCEL file in a different location.... i need a code to password protect the copied file in different location from opening by other users.

A: The Workbook.SaveAs method includes the ability to add a password to the saved workbook. See the Office Dev Center reference page.

A: You the SaveAs method on the workbook and use the Password option
dim wb as workbook

rest of code
wb.SaveAs Filename:="your_filename", Password:="xxxxxx"


text:
Q: WinForms Designer doesn't locate static resource I have several comboBox controls I want to fill with a 10 items, lets say 0-9.
Instead of configuring it like this:
this.comboBox1.Items.AddRange(new object[] {
"0",
"1",
"2",
"3",
"4"});

I added a following variable in my Form.Designer.cs file
static object[] Selection = { "off", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"};

this.comboBox1.Items.AddRange(Selection);

This runs fine, but when I want to view it in the designers preview, it says:
"undeclared variable "Selection" and deletes all my Add.Range lines [insertangrysmiley]
Why doesnt he find it, its in the same class, right in the beginning...

A: Instead of writing
    this.comboBox1.Items.AddRange(Selection);

in InitializeComponent() function
write it outside the function.

A: Remove the static property and do not make Selection a member of the Form class. write these two line near each other inside the Form1.Designer.cs, at the end of InitializeComponent() function.
object[] Selection = { "off", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"};
this.comboBox1.Items.AddRange(Selection);

this way it wont give you any error, and you can preview your form!
but still you can't see it in the preview mode, because it's a combobox. it's better to use a listbox instead! ;)


text:
Q: Java Applet won't launch under macOS I'm attempting to start a Java applet under macOS with java -jar HuffmanShannonFano.jar and get this error message:
jakob@Jakobs-MacBook-Air ~ % java -jar /Users/jakob/Downloads/Hufmann\ Shannon-Fano/HuffmanShannonFano.jar
Exception in thread "main" java.lang.NoClassDefFoundError: com/apple/eawt/ApplicationListener
    at de.tillwiebke.util.MacIntegration.integrate(MacIntegration.java:42)
    at HuffmanShannonFano.main(HuffmanShannonFano.java:53)
Caused by: java.lang.ClassNotFoundException: com.apple.eawt.ApplicationListener
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:641)
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:520)
    ... 2 more

Under Linux the Applet launches just fine. What can I do?

A: That class, now obsolete, was the mechanism by which a Java app could integrate into macOS. Specifically, to hook into Open, Preferences, About, Quit menu items / events.
That class was deprecated and then eventually removed from the modern versions of Java.
If you have the source code, you can replace those calls with calls to com.apple.eawt.Application.set*Handler() APIs.
See this Answer on Question What is the alternative for deprecated com.apple.eawt.ApplicationListener.