text:
Q: android AppCompatRadioButton get text if check I try to get text if AppCompatRadioButton is check by button click.
this is layout :
<LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="horizontal">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="status"
                android:textColor="#f2ff00" />

            <RadioGroup
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="horizontal">

                <android.support.v7.widget.AppCompatRadioButton
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:id="@+id/radioButtonFull"
                    android:text="full"
                    android:textColor="#f2ff00"
                    app:buttonTint="#ffffff" />

                <android.support.v7.widget.AppCompatRadioButton
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:id="@+id/radioButtonEnd"
                    android:textColor="#f2ff00"
                    app:buttonTint="#28ff1c"/>

            </RadioGroup>

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/buttonSearch"
                android:textColor="#ffffff"/>

        </LinearLayout>

this is my code :
AppCompatRadioButton rb_full = (AppCompatRadioButton)view.findViewById(R.id.radioButtonFull);
    rb_full.setText("This is full !");
    AppCompatRadioButton rb_end = (AppCompatRadioButton)view.findViewById(R.id.radioButtonEnd);
    rb_end.setText("This is end !");
    String status;
    if(rb_full.isChecked()){
        status = "Full, please delete something";
    }
    if(rb_end.isChecked()){
        status = "End, please select one of it";
    }

    bt_Search = (Button) view.findViewById(R.id.buttonSearch);
    bt_Search.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v) {
            Toast.makeText(getActivity().getApplicationContext(), status, Toast.LENGTH_SHORT).show();
        }
    });

I try get string status if AppCompatRadioButton is check by button click.
but when click button, Toast show nothing.
How to fix it ?

A: <RadioGroup
            android:id="@+id/rg"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <android.support.v7.widget.AppCompatRadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/radioButtonFull"
                android:text="full"
                android:checked="true"
                android:textColor="#f2ff00"
                app:buttonTint="#ffffff" />

            <android.support.v7.widget.AppCompatRadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/radioButtonEnd"
                android:textColor="#f2ff00"
                app:buttonTint="#28ff1c"/>

</RadioGroup>

JAVA
 final RadioGroup rg  = (RadioGroup) findViewById(R.id.rg);
    bt_Search.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v) {
            int selectedId = rg.getCheckedRadioButtonId();
            if(selectedId == R.id.radioButtonFull)
            status = "Full, please delete something";
            else
            status = "End, please select one of it";
            Toast.makeText(getActivity().getApplicationContext(), status, Toast.LENGTH_SHORT).show();
        }
    });

A: You need to implement OnClickListener to change value in variable Status. You can do it in 2 ways:
1) Implement OnCheckedChangeListener on the radio group itself:
RadioGroup radioGroup = (RadioGroup) findViewById(R.id.yourRadioGroup);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
    {
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            // checkedId is the RadioButton selected
            if(checkedId == R.id.radioButtonFull)
                status = "Full, please delete something";
            else
                status = "End, please select one of it";
        }
    });

2) The Second way will be to implement OnClickListener for both the radio button but that would be redundant code.So I will suggest you to use the 1st approach only.

A: You can get selected radiobutton values on button click this way,Check this
public class MyActivity extends Activity {

  private RadioGroup radioSexGroup;
  private RadioButton radioSexButton;
  private Button btnDisplay;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    addListenerOnButton();

  }

  public void addListenerOnButton() {

    radioSexGroup = (RadioGroup) findViewById(R.id.radioSex);
    btnDisplay = (Button) findViewById(R.id.btnDisplay);

    btnDisplay.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

                // get selected radio button from radioGroup
            int selectedId = radioSexGroup.getCheckedRadioButtonId();

            // find the radiobutton by returned id
                radioSexButton = (RadioButton) findViewById(selectedId);

            Toast.makeText(MyActivity.this,
                radioSexButton.getText(), Toast.LENGTH_SHORT).show();

        }

    });

  }
}


text:
Q: Column X of relation Y contains null values When inserting first admin into my database I get this error message and don't know how to solve it:
[Nest] 13803   - 04/27/2021, 23:03:02   [TypeOrmModule] Unable to connect to the database. Retrying (6)... +3176ms
QueryFailedError: column "name" of relation "admin" contains null values

Other tables work just fine so far and without errors.
Column name in admin table is not null it contains value:

Register service:
async register(registerInput: RegisterInput): Promise<void> {
    const { key, name, password, email } = registerInput;

    const hashedKey = createHash('sha256')
      .update(key)
      .digest('hex');

    const invite = await this.invitesRepository.findOne({ key: hashedKey });

    if (!invite) {
      throw new UnauthorizedException();
    }

    const newAdmin = await this.adminsRepository.create({
      name,
      password,
      email,
    });
    await this.adminsRepository.save(newAdmin);

    await this.invitesRepository.delete({ id: invite.id });
  }

A: I deleted dist directory and rebuilt the code. This solved the issue.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why are generators defined oppositely in Weinberg's vs. Maggiore's QFT books? I've been confused about the sign conventions used in Weinberg's QFT book for a long time.
Here's my question: The generators $J^{\mu\nu}$ are defined in this book as
$$U(1+\omega)=1+\frac{i}{2}\omega_{\mu\nu}J^{\mu\nu}\tag{2.4.3}$$
(on page 59), and in Maggiore's book as $$U(1+\omega)=1-\frac{i}{2}\omega_{\mu\nu}J^{\mu\nu}.$$
The metric conventions are the opposite and the former uses passive transformation while the latter uses active transformation.
If the parameters ${\omega^\mu}_\nu$ are the same in the two cases,  then the left hand sides of the two equations should represent opposite transformations. On the other hand, the right hand sides show they are the same. What accounts for the discrepancy?


text:
Q: unable to generate CSS file sass-loader webpack I am trying to use sass-loader to convert SCSS files to css(Required to have physical file). Styles are getting applied but unable to see generated .css files .
//webpack.config.js

var ExtractTextPlugin = require("extract-text-webpack-plugin");

module.exports = {
    entry: './src/index.js',
    output: {
        path: __dirname + '/public',
        filename: 'bundle.js'
    },
    devServer: {
        contentBase: __dirname + '/public'
    },
    module: {
      loaders: [
          {test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader'},
          {test: /\.scss$/, loader: ExtractTextPlugin.extract('css-loader!sass-loader')}
      ]
    },
    plugins: [
       new ExtractTextPlugin("style.css")
   ]
}

Full source code is available at github repo

A: I've seen the source code. I'm sure it's because of you're still using webpack version 1 syntax but what you installed was webpack v2. Webpack2 has a different syntax than the previous version.
Using webpack v2 your webpack.config.js will look like this:
module: {
        rules: [ // from 'loaders' to 'rules'
            {
                test: /\.js$/,
                loader: 'babel-loader',
                exclude: /node_modules/,
            },
            {
                test: /\.sass$/,
                exclude: /node_modules/,
                loader: ExtractTextPlugin.extract({
                  fallbackLoader: 'style-loader',
                  loader: ['style-loader','sass-loader']
                })
            }
        ]
    },

    plugins: [
        new ExtractTextPlugin('bundle.css') // what the output file (css) is going to be
    ]

Hope this helps.


text:
Q: Proper way to customize an InfoPath web-based form with CSS and Javascript I need to add custom CSS and JavaScript to an InfoPath web-based form.
For which I am planning to export the source files and customize the view1.xsl file.
If I add the customizations in the header, they will be removed by InfoPath Designer next time I edit the form.
If I add the customizations in the body, some other developer may remove them.
My question is - what is the proper way to add customizations? Thank you!

A: In the page where your infopath is shown, add a script editor web part and there add your code or the url of css files. I've even add a visual web part to prefill infopath's fields with data (like last month salary) .


text:
Q: How Do I Stop or Disable Scheduler if I've found a possible PermGen memory leak with Tomcat and Akka? I'm trying to figure out if it's possible to disable the Akka Scheduler thread as I might have found a memory leak(?).
I have a Java-Spring application running on Tomcat that registers my Akka ActorSystem with basic configuration - i.e. I haven't provided an application.conf, I'm just going with the standard defaults for everything for the moment.
The work done by the actors that get spawned is just simple creation of a Spring RestTemplate object that get some JSON from a service and Jackson is then used to create some objects.
On my production servers, which are under fairly large load during retail sales, I've recently noticed my PermGen space slowly creeping up now I've put in the ActorSystem.
So to find the source of the problem I ran the application locally, let my Tomcat container initialise the Spring application - which in turn instantiates an actor system. Simple. All good. Until...
I started looking at VisualVM memory Sampling.
Without even hitting a page - so the app has started up and NOTHING else has taken place, no requests, nada... the sleeping Thread of the scheduler "myActorSystem-scheduler-1" appears to be using memory. Grabbing memory at about 8kb/sec. (possibly per "tick").
I left VisualVM running overnight and came in to find 300MB of PermGen was just GONE.
My production servers have a different configuration than development to some degree, but when the server is sitting idle the ONLY THING that's using memory is this scheduler. If the server isn't interacting with anything and the scheduler isn't even used - AT ALL - it really shouldn't be skimming my memory.
I haven't configured the Akka actor system to do anything that isn't out of the box.
If you debug akka.dispatch.AbstractNodeQueue you'll find that this constructor is called on every 'tick'...
private volatile Node<T> _tailDoNotCallMeDirectly;

protected AbstractNodeQueue() {
   final Node<T> n = new Node<T>();
   _tailDoNotCallMeDirectly = n;
   set(n);
}

Instantiating an object that gets set to a "value" variable reference inside this class:
public class AtomicReference<V>  implements java.io.Serializable {
private static final long serialVersionUID = -1848883965231344442L;

private static final Unsafe unsafe = Unsafe.getUnsafe();
private static final long valueOffset;

static {
  try {
    valueOffset = unsafe.objectFieldOffset
        (AtomicReference.class.getDeclaredField("value"));
  } catch (Exception ex) { throw new Error(ex); }
}

private volatile V value;

/**
 * Sets to the given value.
 *
 * @param newValue the new value
 */
public final void set(V newValue) {
    value = newValue;
}

I've seen Tomcat configurations such as:
-XX:+CMSClassUnloadingEnabled -XX:+CMSPermGenSweepingEnabled

that enable Tomcat to sweep the PermGen space and clean it out if it can. ("can" - this is the garbage collector we're talking about).
On the production servers I added these lines and my servers are actually using less PermGen on average than normal, now. This is a good thing, however:

*

*is this really necessary though? If this is a genuine memory leak I'd rather not just "work-around" the problem especially since I've never had PermGen issues before I started using this very basic Akka ActorSystem implementation.

*Will instantiating such a static class on every tick not put something into the PermGen space every time? Am I wrong in thinking this is a memory leak?

*Can I turn off the akka Scheduler if I DON'T NEED to schedule an actor work to trigger in the future?. (I only want to trigger actors on requests as they arrive). I only see config for a scheduler's tick time in the docs. It would be useful to deactivate it, to test this issue. Or am I missing something, that the Scheduler is very important? As it never does anything even with my App getting hit and creating actors. The thread just sleeps and eats my memory.
Any ideas peeps? Many thanks.


text:
Q: Group multiple iOS applications Let me set the stage first. Say a larger organization has a single iOS application. This worked just fine in the past, with new features being added to the app. The problem is that the application has become too large and hence difficult to manage. Cramming all new functionality into a single app is no longer feasible. To make things worse, organization does not want to have mutliple applications, as it would lead to fragmented user experience, which is not ideal. Question is... Is there something similar to "App Bundles" that would allow users to install multiple applications belonging to same organization without the need to individually install them? Unfortunately "App Bundles" require tier 1 applications (i.e. paid ones).

A: There is nothing similar to "App Bundles" on iOS other than App Bundles.
However, you can have multiple apps in the store and use a url scheme for each app to see if a particular app can be launched when needed by a user -- for example, from a menu.
let appURL = NSURL(string: "myscheme://")
let appStoreURL = NSURL(string: "https://itunes.apple.com/ca/app/myappname/id99999999?mt=8")

if (UIApplication.sharedApplication().canOpenURL(appURL!)){
    // app is installed, launch it
    UIApplication.sharedApplication().openURL(appURL!)
} else {
    // app is not installed, go get it
    UIApplication.sharedApplication().openURL(appStoreURL!)
}

If not, you can deep link to the correct page in the app store and the user can install them.  We use this technique to provide a way for users to access our constellation of apps from a single "launcher" app.

A: Depending on how many "subApps" you have I would recommend a tabBarController. I personally did this in a case similar to yours where we were adding new features to our app. You could also group this with @Wain 's idea to have a toggle feature to turn on or off parts of the app.


text:
Q: can't uninstall package with pip I have installed pillow package, and uninstall attempt with sudo pip uninstall pillow leads to this message:
Not uninstalling Pillow at /usr/lib/python2.7/dist-packages, owned by OS

Manual uninstall doesn't work, because pip writes down installed packages somewhere, successfuly blocking me from installing the package again.

A: This python library is important to keep Linux Mint Cinnamon running. It could be removed with sudo apt-get remove python-pil (not pip), but it would most likely break the operating system.

A: This should fix the problem, as it fixed mine on Ubuntu 14.x
install pip (even if it is already installed), securely download get-pip.py from here https://pip.pypa.io/en/stable/installing/
Then run the following:
sudo python get-pip.py


text:
Q: In WebRTC, when one user needs TURN but the other user does not, will traffic between them all go through TURN server? What is WebRTC's behavior in establishing peer connection between following two users?

*

*User A's network involves NAT/router such that direct connection to it is not possible, and it requires TURN relay.

*User B's network can support direct connection.

I assume traffic from user B to user A must go through TURN server.
However, does traffic from user A to user B also have to go through TURN?
In other words, when one of two users require TURN due to network constraints, will all traffic between them go through TURN server regardless of whether or not the other user supports direct connection?

A: The ICE protocol will attempt a direct connections in either direction: if one peer is directly reachable from the other, then traffic will take the direct route in both directions.  It is only if neither peer can reach the other that TURN will be used.
Note, however, that ICE might time out before the direct connection is established, so even if the peers are reachable, the data might occasionally go through the TURN server.


text:
Q: Plot legend extracted from grob separately I have a ggplot object:
ggplot(plot1,aes(x = c, y = value, colour = variable, linetype = variable,size = variable)) +
    geom_line() +
    scale_x_continuous(breaks=seq(1,10,1)) +
    #scale_y_continuous(breaks=seq(0,1, 0.1))+
    scale_colour_manual(values=c("blue3","red3")) +
    scale_linetype_manual(values = c(3,1)) +
    scale_size_manual(values = c(0.6,0.3)) +
    xlab("b") +
    ylab("a") +
    theme_bw() +
    theme(axis.text=element_text(size=5),
          axis.title=element_text(size=5),
          axis.line = element_line(size=0.25),
          axis.ticks=element_line(size=0.25),
          panel.grid.major = element_blank(),
          panel.grid.minor = element_blank(),
          panel.border = element_blank(),
          panel.background = element_blank(),
          legend.position="right" ,
          legend.direction="vertical",
          legend.title=element_blank(),
          legend.text=element_text(size=8),
          legend.background=element_blank(),
          legend.key=element_blank())

I would like to plot the corresponding legend separately.
Is it possible to extract it somehow?
I tried using this function to save the legend a a grob, but it only returns and empty quartz window but no legend.
g_legend<-function(a.gplot){
tmp <- ggplot_gtable(ggplot_build(a.gplot))
leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
legend <- tmp$grobs[[leg]]
return(legend)}

source: https://github.com/hadley/ggplot2/wiki/Share-a-legend-between-two-ggplot2-graphs

A: Using a simplyfied version of your plot code:
# base plot
p1 <- ggplot(plot1,aes(x=c, y=value, colour=variable, linetype=variable, size=variable)) +
    geom_line()

# extract the different legends
leg1 <- p1 + guides(linetype=FALSE, size=FALSE)
leg2 <- p1 + guides(colour=FALSE, size=FALSE)
leg3 <- p1 + guides(colour=FALSE, linetype=FALSE)
legend.colour <- gtable_filter(ggplot_gtable(ggplot_build(leg1)), "guide-box")
legend.linetype <- gtable_filter(ggplot_gtable(ggplot_build(leg2)), "guide-box")
legend.size <- gtable_filter(ggplot_gtable(ggplot_build(leg3)), "guide-box")

leg1Grob <- grobTree(legend.colour)
leg2Grob <- grobTree(legend.linetype)
leg3Grob <- grobTree(legend.size)

p2 <- p1 + guides(colour=FALSE, linetype=FALSE, size=FALSE)

# final plot were you can place the legends were you want them
finplot <- p2 +
  annotation_custom(grob = leg1Grob, xmin = ??, xmax = ??, ymin = ??, ymax = ??) +
  annotation_custom(grob = leg2Grob, xmin = ??, xmax = ??, ymin = ??, ymax = ??) +
  annotation_custom(grob = leg3Grob, xmin = ??, xmax = ??, ymin = ??, ymax = ??)

Replace the ?? with the coordinates in your plot were you want to put your legends.
When you want to plot the legends seperately, make a blank plot with geom_blank


text:
Q: How to delete parent directories without deleting its children directories in git? I have a git repository that has the file structure of /react-projects/programming-todo-list/programming-todo-list/*
I want to delete the upper directories /react-projects/programming-todo-list so that it ends up looking like this : programming-todo-list/*
Is there a way to delete the upper directories without deleting the children directories?

A: git mv programming-todo-list ../.. is enough if you don't want to impact your past commits (which would still display programming-todo-list in its former place).
If you can rewrite the history of your repository, then git filter-repo (Python-based, to be installed first) is the right tool, using path-based filtering:
git filter-repo --path-rename react-projects/programming-todo-list/programming-todo-list:programming-todo-list


text:
Q: Product editing page (admin panel ) Not working HTTP ERROR 500 hey guys i was doing import export process for product. now when i go to backend of my old store for product customization . Page is not opening & it shows error . Anyone know how to deal with it Urgent.
This page isn't Working
rdskingdom.com is currently unable to handle this request.
HTTP ERROR 500


text:
Q: Populate / store data from csv into django admin I want to get data from CSV and populate it to Django admin. but due to foreign key user I am not getting the desired result.
def handle(request):
        df = pd.read_excel('testdata.xlsx')
        obj=Account.objects.filter(email=df.user[0])

        for session_date,session_time,session_name,duration,i in zip(df.session_date,df.session_time,df.session_name,df.duration,obj):

            models = GuidedSession(session_date=session_date,session_time=session_time,session_name=session_name,duration=duration,user=i)
            # print(i)
            print(models
            # models.save()

        return HttpResponse(status=200)

(Views.py)
class Account(AbstractBaseUser):
    email                   = models.EmailField(verbose_name="email", max_length=60)
    username                = models.CharField(max_length=30)
    date_joined             = models.DateTimeField(verbose_name='date joined', auto_now_add=True)
    last_login              = models.DateTimeField(verbose_name='last login', auto_now=True)
    is_admin                = models.BooleanField(default=False)
    is_active               = models.BooleanField(default=True)
    is_staff                = models.BooleanField(default=False)
    is_superuser            = models.BooleanField(default=False)

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username']

    objects = MyAccountManager()

    def __str__(self):
        return self.email

class GuidedSession(models.Model):
    session_date = models.CharField(max_length=200)
    session_time = models.CharField(max_length=200)
    session_name = models.CharField(max_length=200)
    duration = models.IntegerField(default=20)
    user = models.ForeignKey(Account, on_delete=models.CASCADE)

    def __str__(self):
        s = str(self.session_name)
        return s

(Models.py)
Let me know the best way to do that.


text:
Q: Multiclasses Classification Neural Network error: "Matrix type cannot be converted to python" I'm trying to build a neural network in order to classify images from people, and predict their ages.
The code is the following:
library(EBImage)
library(keras)

# Read images
setwd('C:\\Users\\smbsv\\Desktop\\UTKFace')

# Get file list with full path and file names
files <- list.files('C:\\Users\\smbsv\\Desktop\\UTKFace', full.names = TRUE, pattern = "jpg$|JPG$")

files

# Select the desired % or number of file by simple random sampling
randomize <- sample(seq(files))

files2analyse <- files[randomize]

files2analyse <- files2analyse[(1:5000)]

files2analyse

mypic <- list()

for (i in 1:length(files2analyse)) {mypic[[i]] <- readImage(files2analyse[i])}

mypic

display(mypic[[1]])
display(mypic[[100]])
display(mypic[[2400]])
display(mypic[[4720]])

# Resize
for (i in 1:length(mypic)) {mypic[[i]] <- resize(mypic[[i]], 128, 128)}

display(mypic[[2400]])
display(mypic[[4720]])

# Reshape
for (i in 1:length(mypic)) {mypic[[i]] <- array_reshape(mypic[[i]], c(128, 128, 3))}

#make this example reproducible
set.seed(1493)

#use 70% of dataset as training set and 30% as test set
sample <- sample(c(TRUE, FALSE), length(mypic), replace=TRUE, prob=c(0.7,0.3))

train  <- mypic[sample]
test   <- mypic[!sample]

filenamesTRAIN <- files2analyse[sample]
filenamesTEST <- files2analyse[!sample]

filenamesTRAIN[10]
display(train[[10]])

filenamesTRAIN[362]
display(train[[362]])

filenamesTEST[25]
display(test[[25]])

filenamesTEST[189]
display(test[[189]])

length(train)
length(test)

trainx <- NULL

trainx <- rbind(trainx, train)
trainx

str(trainx)

testx <- NULL
testx <- rbind(testx, test)

str(testx)

#change files names to only images names (TRAIN)

for (i in 1:length(filenamesTRAIN)) {filenamesTRAIN[i] <- substring(filenamesTRAIN[i], 32)}

#change files names to only images names (TRAIN)

for (i in 1:length(filenamesTEST)) {filenamesTEST[i] <- substring(filenamesTEST[i], 32)}

filenamesTRAIN[27]
filenamesTRAIN[147]

filenamesTEST[189]
filenamesTEST[4]

#extract classes from filename (pattern: [age]_[gender(0=male,1=female)]_[race(from 0 to 4, denoting White, Black, Asian, Indian, and Others)]_[date&time].jpg)
library(stringr)

trainy <- NULL

for (i in 1:length(filenamesTRAIN)) {trainy[i] <- str_split(filenamesTRAIN[i], "_")[[1]][1]}

filenamesTRAIN[20]
trainy[20]
filenamesTRAIN[100]
trainy[100]

testy <- NULL

for (i in 1:length(filenamesTEST)) {testy[i] <- (str_split(filenamesTEST[i], "_")[[1]][1])}

filenamesTEST[16]
testy[16]
filenamesTEST[185]
testy[185]

# One Hot Encoding
class(trainy[4])
for (i in 1:length(trainy)) {trainy[i] <- as.numeric(trainy[i]) - 1} # -1 avoid 1 more column when use "to_categorical"
for (i in 1:length(testy)) {testy[i] <- as.numeric(testy[i]) - 1}

trainLabels <- to_categorical(trainy)
testLabels <- to_categorical(testy)

filenamesTEST[7]
testLabels    # rows: people ; columns : labels (age)

# Model
model <- keras_model_sequential()
model %>%
  layer_dense(units = 256, activation = 'relu', input_shape = c(3498)) %>%
  layer_dense(units = 128, activation = 'relu') %>%
  layer_dense(units = 116, activation = 'softmax')
summary(model)

# Compile
model %>%
  compile(loss = 'crossentropy',
          optimizer = optimizer_rmsprop(),
          metrics = c('accuracy'))

# Fit Model
history <- model %>%
  fit(trainx,
      trainLabels,
      epochs = 30,
      batch_size = 32,
      validation_split = 0.2)

Everything work until i try to fit the model, and it gives me this error:
Error: Matrix type cannot be converted to python (only integer, numeric, complex, logical, and character matrixes can be converted

I think that the problem is the datatype of "trainx" and "trainLabels".
If it can be usefull, this is the returned type for these variables:
trainx:
>str(trainx)

List of 3498
$ : num [1:128, 1:128, 1:3] 0.113 0.123 0.121 0.117 0.118 ...
$ : num [1:128, 1:128, 1:3] 0.108 0.127 0.163 0.222 0.29 ...

...
- attr(*, "dim")= int [1:2] 1 3498
 - attr(*, "dimnames")=List of 2
  ..$ : chr "train"
  ..$ : NULL

trainLabels:
> str(trainLabels)
num [1:3498, 1:116] 0 0 0 0 0 0 0 0 0 0 ...

How can i solve this error?


text:
Q: How to change the number of rows using a st-template I've created a st-template that contains specific pagination functionality.
Here is mine the div that calls the st-template:

Within this pagination we have a dropdown/button where the user can select the number of rows to display within the table.

                <input
                    id="items-per-page-{{page * 10}}"
                    name="items-per-page-options"
                    type="radio"
                    value=""
                    role="menuitemradio"
                    aria-checked="true"
                    checked
                    ng-model="itemsPerPage"
                >

                     {{ page * 10 }}

So 'itemsPerPage' updates in the template but does not reach the , which is in another html file.
I have been looking for an answer for a few hours and haven't really found one.  This is my first experience working with smart-table and angularJS so I may not be using the correct key words.
Any help would be appreciated.

A: I ended up moving the items per-page html out of the template into the datatable html file.  I created an array of static values that represents the number of row to display ['10','20','30','40','50'].  Once the user selects one I send in the ng-model itemPerPage and the items update to that selection.
The reason it wasn't working in the template was because of the ng-repeat created a child scope so when I used ng-model it was not modify the original scope.


text:
Q: call a function after program has been idle for a given time My Tkinter-based program needs to periodically perform some "heavy" maintenance functions.
Since it is a program that is running continuously, I was thinking of launching those functions only after a given amount of idle time.
How do you do it in Tkinter? I found about about after_idle in http://etutorials.org/Programming/Python+tutorial/Part+III+Python+Library+and+Extension+Modules/Chapter+16.+Tkinter+GUIs/16.9+Tkinter+Events/, but that gets called just when the event loop is idle. I need it to run my functions, say, after 10 minutes of idle time instead.
~~~
Mr.Steak gave the answer I needed - I just modified it slightly as follows to be able to perform different tasks at different intervals, using the idletime variable :
import time
from Tkinter import *

root = Tk()

def resetidle(*ignore):
    global idletime
    for k in idletime: k['tlast']=None

def tick(*ignore):
    global idletime
    t=time.time()   # the time in seconds since the epoch as a floating point number
    for k in idletime:
        if not k['tlast']:
            k['tlast'] = t
        else:
            if t-k['tlast']>k['tmax']:
                k['proc']()
                k['tlast'] = None
    root.after(5000, tick)   # reset the checks every 5''

idletime=[{'tlast':None,'tmax':60,'proc':test1},               # every 1'
      {'tlast':None,'tmax':3600,'proc':test2}]    # every 1h
root.after(5000, tick)
root.bind('<Key>', reset)
root.bind('<Button-1>', reset)
root.mainloop()

A: In the following example, the tick function is called every second. After 5 seconds, a message is printed, unless a key or mouse button 1 were pressed.
import time
from Tkinter import *

root = Tk()
running = None

def reset(*ignore):
    global running
    running = None

def tick(*ignore):
    global running
    if not running:
        running = time.time()
    elif time.time() - running > 5:
        print 'I waited 5 seconds...'
        running = None
    root.after(1000, tick)

root.after(1000, tick)
root.bind('<Key>', reset)
root.bind('<Button-1>', reset)
root.mainloop()


text:
Q: If I pass layers to two Keras models and Train only one ,will both the model share weights after the former is trained I tried to build a simple Autoencoder using Keras for this I started with a single fully-connected neural layer as an encoder and as a decoder.
> input_img = Input(shape=(784,))
>encoded = Dense(encoding_dim,activation='relu')(input_img)
>decoded = Dense(784, activation='sigmoid')(encoded)
>autoencoder =Model(input_img, decoded)

I also created a separate encoder module with the help of
encoder = Model(input_img, encoded)

As well as the decoder model:
encoded_input = Input(shape=(32,))
# retrieve the last layer of the autoencoder model
decoder_layer = autoencoder.layers[-1]
# create the decoder model
decoder = Model(encoded_input, decoder_layer(encoded_input))

Then I trained the model
autoencoder.fit(x_train, x_train,
                epochs=50,
                batch_size=256,
                shuffle=True,
                validation_data=(x_test, x_test))

but even if i didn't train my encoder and decoder, Those are sharing the weights of autoencoder even if I passed the layers before training. I trained only the encoder but both encoder and decoder are getting trained.
encoded_imgs = encoder.predict(x_test)
decoded_imgs = decoder.predict(encoded_imgs)

A: I should have been more careful while reading the text.
If two Keras models are sharing some layers, when you train the first model, the weights from the shared layers will be updated automatically in the other model.
https://keras.io/getting-started/functional-api-guide/
This blog illustrates the use of shared layers nicely.
https://blog.keras.io/building-autoencoders-in-keras.html/


text:
Q: With angular-fullstack, socket.io doesn't update my controller (but it sync the 'awesomeThings' example) I tried a lot of things on my tests, but in the end I came back to the original code from angular-fullstack, and then I tried to clone the working example. Anyway, I cannot get it working: My changes don't synchronize between clients, as the example ones does.
This controller is the simplest one, and I was trying to use it as an example of how to work with socket.io with the rest of the app.
My Controller (simplified)
'use strict';

(function() {

class AdminController {
  constructor($http, $scope, socket) {
    this.$http = $http;
    this.info = [];
    $http.get('/api/infoclan').then(response => {
      this.info.push(response.data);
      socket.syncUpdates('infoclan', this.info);
    });
  }

  save() {
      this.$http.post('/api/infoclan/update', this.info[0]);
  }
}

angular.module('eecrApp.admin')
  .controller('AdminController', AdminController);
})();

I'm using push because it was giving me the array.push error, as the response is a JSON, and in the socket.service.js the service try to push the 'new item':
<line 41>
if (oldItem) {
            array.splice(index, 1, item);
            event = 'updated';
          } else {
            array.push(item);
          }

With my scope as an array, it save, everything works fine...except the change don't synchronize  between clients (I need to refresh).
I tried different approaches...with the same result.
Index.js on Server
'use strict';

import {Router} from 'express';
import * as controller from './infoclan.controller';
import * as auth from '../../auth/auth.service';

var router = new Router();

router.get('/', controller.index);
router.post('/update', auth.hasRole('admin'), controller.update);
router.post('/', controller.create);

export default router;

Infoclan.model.js8
'use strict';

var mongoose = require('bluebird').promisifyAll(require('mongoose'));
import {Schema} from 'mongoose';

var InfoclanSchema = new mongoose.Schema({
  identificador: { //It'll always save the same document, as there's only one infoclan
    type: String,
    default: '1'
  },
  nombre: {
    type: String,
    default: 'Elite España'
  },
  twitter: {
    type: String,
    default: 'EliteEspanaCR'
  },
  texto: {
    type: String,
    default: 'Cambiar!test'
  }
});

export default mongoose.model('Infoclan', InfoclanSchema);

I don't know what I should try next :(

A: Ok, I found it :) :+1:
The problem were o the API, with the GET Index. I was doing this:
export function index(req, res) {
  Infoclan.findOneAsync({'identificador': '1'}, '-_id nombre twitter texto')
    .then(handleEntityNotFound(res))
    .then(respondWithResult(res))
    .catch(handleError(res));
}

Without the _id, it couldn't identify the oldItem, and then it never updates, only creates.
I need to send the _id of every object, then :)
This is the correct code:
export function index(req, res) {
  Infoclan.findOneAsync({'identificador': '1'})
    .then(handleEntityNotFound(res))
    .then(respondWithResult(res))
    .catch(handleError(res));
}


text:
Q: Understanding crossfilter.js bit-twiddling hack I found it on crossfilter.js description and am trying to understand what this line means

Crossfilter uses sorted indexes (and a few bit-twiddling hacks) to
  make this possible, dramatically increasing the performance of live
  histograms and top-K lists.

The sorted-index refers to the use of index like in databases, I think. To avoid doing full-table scans. Each dimension has an index on which filtering is done. This leads to incremental filtering (filter each index one by one) and finally when filtered data is finally generated, events are fired.
But looking at the code I could not understand what the hack is, what is it used for and how. Can anyone explain the purpose of bit-twiddling here ?

A: At the beginning there's this declaration:
m = 0, // a bit mask representing which dimensions are in use
A "bit mask" is a simple and efficient way to keep track of a list of true/false options. Let's say you create a listing of cars for sale and you want to set four extra parameters of each car listed: 4x4, ABS, ESP, climatronic. You could define a car object like this:
MyCar = { brand : "Mercedes",
          extras : {
              "4x4" : false,
              "ABS" : true,
              "ESP" : false,
              "climatronic" : true
          }
        }

These extras are easy to set and retrieve: if( MyCar.extras['4x4'] ){ /* display a ✓ */ }. It's easy, simple, readable but in some cases may require too many resources to process (think: nested loops over a huge collection).
So we may create an array where each index corresponds to a feature, right?
MyCar = {  brand : "Mercedes",
           // 1: 4x4, 2: ABS, 3: ESP, 4: climatronic
           extras : [ false, true, false, true ]
        }

Now to check whether given car has 4x4 you need to use if( MyCar.extras[0] ){ /* display a ✓ */ }. It's less readable (you need to consult documentation to know which feature is under which index) but probably faster an requires less memory.
The concept of a bitmask is similar, but uses numbers instead of arrays. extras : [ false, true, false, true ] could be shortened to extras : [ 0, 1, 0, 1 ] and 0101 is a binary representation of the number 5. So a Car object with a bitmask describing its features could look like this:
MyCar = {  brand : "Mercedes",
           extras : 5
        }

This looks completely unintuitive, but should be very fast and lightweight. How do you check whether the car has 4x4? Well, 4x4 is represented as 1000 (binary representation of 8) so:
if( !!(MyCar.extras & 8) ){ /* display a ✓ */ }
so yeah, now we talk about hacks just by the look of this code. It's really simple but looks cryptic if you haven't played with bitwise operators before. To explain further: our car has the extras attribute set to 5, which in binary is 0101 and we want to check if the left-most bit is set to 1. Bitwise AND operation returns a number that has 1's only where both operands have a 1.
    0101  // 5
AND 1000  // 8
  = 0000

Now let's check for ABS, which is the 2nd bit from the left (0100, i.e. 4).
var hasABS = !!( MyCar.extras & 4 ); // true

because
    0101  // 5
AND 0100  // 4
  = 0100

How to set the ESP to true? Simple:
MyCar.extras |= 3;  // now extras == 7

what has happened? a binary OR returns a number that has 1's where either of its operands has a 1 bit.
5 | 3 = 0101 | 0010 = 0111 = 7;
Now to set the ABS to false you'd use
MyCar.extras ^= 4;

I'll leave the workings of binary XOR as an exercise to the reader, but I hope you get the gist of using bitmasks and "bit twiddling" now.


text:
Q: Difference between MAMP and DigitalOcean LAMP Ubuntu 14.04 server messing up Joomla Custom Form Field I wrote a Custom Form Field on a Joomla 2.5 site.
My form field selects an id value and tag name from a database table, and allows you to select multiple checkboxes.  Pretty simple.
My problem is that the code works perfectly on my dev server (MAMP, standard settings), but doesn't work on my DigitalOcean Ubuntu 14.04 VPS.

MAMP (above)
VS
DigitalOcean (below)

So yeah, I'm looking for ideas here.  My main thought is that it's in the PHP Settings, in Disabled Functions.
MAMP has no disabled functions, Digital Ocean has the following:
Disabled Functions  pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority,
Any ideas?
UPDATE: I commented out the disabled functions for a moment, restarted the server.  Got some different console errors which was interesting, but it didn't fix the problem.  Any other suggestions?
UPDATE 2:  Solved by changing filename to all lowercase on production server.  Answer below shows detail.

A: This can happen when Joomla doesn't find the custom form field definition — in those cases it reverts to a standard text input element.
Depending on how you moved the site from your MAMP setup to the live Ubuntu VPS you may have missing files.
If you followed the Joomla standard for custom form fields you should have something like this:
/components/com_mycomponent/models/fields/mycomponentmultitags.php
I would check that your custom field file exists on the VPS and that it's permissions are set correctly (644 should do it).
Update
In respect to the cause of the problem (i.e. filename case). So file systems are case sensitive and some aren't, and some are case aware (i.e. show the case) but not case sensitive. I should've picked up you were on MAMP (ie. a Mac), OSX runs on HFS+. HFS+ is, by default, not case sensitive but is case preserving. So calling the all lowercase name of the file will work on MAMP but not on Ubuntu (because it is case sensitive.
Which in this case tak you back to the fact that Joomla (aka PHP) couldn't find the custom form field definition (aka the file CategoryCheckBoxes.php because it was looking for categorycheckboxes.php)

A: Okay so I got it to work, but I don't like not knowing why it worked.
Again, it worked on development (MAMP) but not on my Production VPS (Standard Ubuntu 14.04 LAMP Apache2)
I changed:
administrator/components/com_mycomponent/models/fields/CategoryCheckBoxes.php
to:
administrator/components/com_mycomponent/models/fields/categorycheckboxes.php
Yes, I made the filename all lowercase and it worked like a charm.  That's all I changed.  Does anyone know why that would happen and why it would differ on the server type?


text:
Q: How to access file on a remote server and get the file data as return value in perl? I want to write a perl script which will read a file on a remote server, alter some parameters inside the file and get whole file data or specific data as a return value.
Actually what I was thinking is to use cpan openssh utility to create a ssh connection, then call the script on the server side, which does all the reading and changing the parameters value. But the problem in this approach is that I will get only success or failure as a return value - not the file data.
Can anyone please tell me how I will achieve this functionality?
Thanks in advance....

A: Here is one way to do what you are asking with Net::SSH::Expect
use Net::SSH::Expect;
my $ssh = Net::SSH::Expect->new (
      host => "some.example.net",
      password=> 'your-password',
      user => 'you',
      raw_pty => 1
    );

my $login_output = $ssh->login();
if ($login_output !~ /Welcome/) {
    die "Login has failed. Login output was $login_output";
}
$ssh->exec("perl -i -pe 'tr/9/a/;' temp.txt");
my $cat=$ssh->exec("cat temp.txt");
print($cat);

The file on the remote server (temp.txt) contains just one line 0123456789
and running the script has this output
$ perl /tmp/a.pl
012345678a

The main point here is that with this module I can log in to a remote machine and execute commands as I would with any other ssh session.


text:
Q: Fortran function in a module not found by subroutine in the same module I am writing a module in Fortran90, Mainly I defined a function inside the module, and a subroutine that uses the function. Here's an excerpt of the module
module Mesh_io
  implicit none
  private
contains
  integer function findkey ( )
    content of this function
  end function
  subroutine getNumber_Mesh ()
    integer :: findkey
    content of the routine
  end subroutine getNumber_Mesh
end module

When compiling I get the following output:
objects/Main.o: In function `__mesh_io_MOD_getnumber_mesh':
Main.f90:(.text+0x9e): undefined reference to `findkey_'

As you can see the function is contained in the module, but for some reason the compiler can not find it.

A: With the declaration of findkey inside the subroutine getNumber_Mesh() you are creating a local variable findkey that hides the function.
With modules, it is not required to declare the return value of functions (of module functions). Simply removing the declaration should do the trick.


text:
Q: Show value of custom category description to single post I'm trying to pull out the description value of the custom category i have created using jetengine (similar to ACF). unfortunately, jetengine doesnt have the option to do this that why i have created my custom shortcode
/* function for programs category description */
  function custom_desc_func() {
  ob_start();
  $terms = get_terms(
  array(
    'taxonomy'   => 'program-episode',
    'hide_empty' => false,
   )
   );
   if ( ! empty( $terms ) && is_array( $terms ) ) {
   foreach ( $terms as $term ) {
    $tid = $term->term_id;
   }
    ?>

            <?php echo get_term_meta(46, 'program-intro-description', true
     ) ?>

    <?php

     }
    return ob_get_clean();
     }
    add_shortcode('custom_desc', 'custom_desc_func');

/* end of function for programs category description */
The code is working but as you can see, im manually adding category id number in the code (46) - how do i make this more dynamic?
e.g

*

*''Post A and Post B'' has ''Cat A'' assigned in them....then I want the custom description of ''Cat A ''to appear on both posts (A & B) on the front end

A: Please check below code and let me know.
function custom_desc_func() {
ob_start();
global $post;
$terms = get_the_terms($post->ID,'program-episode');
if ( ! empty( $terms ) && is_array( $terms ) ) {
foreach ( $terms as $term ) {
 $tid = $term->term_id;
}
?>

<?php echo get_term_meta($tid, 'program-intro-description', true); ?>

<?php
}
return ob_get_clean();
}
add_shortcode('custom_desc', 'custom_desc_func');


text:
Q: How to run lilypond-book in LaTeX? Lilypond, as you might know, is a computer program and file format for music engraving. I've wanted to include music in LaTeX PDF documents using lilypond-book (A Lilypond executable file), but I don't really understand how. This might be a silly question; I am a novice at these things. Can you please clearly inform me on how to use lilypond-book?

A: Have you checked the section on this in the Lilypond documentation?
http://lilypond.org/doc/v2.20/Documentation/usage/lilypond_002dbook
I personally didn't like this automated process, because it creates a bunch of auxiliary files, but anyway...
When I needed to create a document with text and musical examples, I produced the examples in Lilypond (PDF files with a cropped fragment of music) and added them in LaTeX files as figures.


text:
Q: linker error on arm neon code I am working on ARM neon code using c intrinsics.  When I compile the file I keep getting the following errors:

c:/program files (x86)/codesourcery/sourcery g++ lite/bin/../lib/gcc/arm-none-ea
  bi/4.3.3/../../../../arm-none-eabi/bin/ld.exe: warning: cannot find entry symbol
   _start; defaulting to 00008020
c:/program files (x86)/codesourcery/sourcery g++ lite/bin/../lib/gcc/arm-none-ea
  bi/4.3.3/../../../../arm-none-eabi/lib\libc.a(lib_a-exit.o): In function 'exit':
  exit.c:(.text+0x28): undefined reference to '_exit'
c:/program files (x86)/codesourcery/sourcery g++ lite/bin/../lib/gcc/arm-none-ea
  bi/4.3.3/../../../../arm-none-eabi/lib\libc.a(lib_a-fstatr.o): In function '_fst
  at_r':
  fstatr.c:(.text+0x1c): undefined reference to '_fstat'
c:/program files (x86)/codesourcery/sourcery g++ lite/bin/../lib/gcc/arm-none-ea
  bi/4.3.3/../../../../arm-none-eabi/lib\libc.a(lib_a-openr.o): In function '_open
  _r':openr.c:(.text+0x20): undefined reference to '_open'
c:/program files (x86)/codesourcery/sourcery g++ lite/bin/../lib/gcc/arm-none-ea
  bi/4.3.3/../../../../arm-none-eabi/lib\libc.a(lib_a-sbrkr.o): In function '_sbrk
  _r':
  sbrkr.c:(.text+0x18): undefined reference to '_sbrk'
c:/program files (x86)/codesourcery/sourcery g++ lite/bin/../lib/gcc/arm-none-ea
  bi/4.3.3/../../../../arm-none-eabi/lib\libc.a(lib_a-writer.o): In function '_wri
  te_r':writer.c:(.text+0x20): undefined reference to '_write'
c:/program files (x86)/codesourcery/sourcery g++ lite/bin/../lib/gcc/arm-none-ea
  bi/4.3.3/../../../../arm-none-eabi/lib\libc.a(lib_a-closer.o): In function '_clo
  se_r':
  closer.c:(.text+0x18): undefined reference to '_close'
c:/program files (x86)/codesourcery/sourcery g++ lite/bin/../lib/gcc/arm-none-ea
  bi/4.3.3/../../../../arm-none-eabi/lib\libc.a(lib_a-isattyr.o): In function '_is
  atty_r':isattyr.c:(.text+0x18): undefined reference to '_isatty'
c:/program files (x86)/codesourcery/sourcery g++ lite/bin/../lib/gcc/arm-none-ea
  bi/4.3.3/../../../../arm-none-eabi/lib\libc.a(lib_a-lseekr.o): In function '_lse
  ek_r':lseekr.c:(.text+0x20): undefined reference to '_lseek'
c:/program files (x86)/codesourcery/sourcery g++ lite/bin/../lib/gcc/arm-none-ea
  bi/4.3.3/../../../../arm-none-eabi/lib\libc.a(lib_a-readr.o): In function '_read
  _r':readr.c:(.text+0x20): undefined reference to '_read'
collect2: ld returned 1 exit status

Can anyone tell me how to rectify these errors?.  All I know is that I have to explicitly define the functions isatty(), fstat etc.  But I don't know where to define them


text:
Q: Как разместить два горизонтальных списка друг над другом справа в header? Мне необходимо разместить два горизонтальных списка друг над другом, уже целый день голову ломаю. Они у меня ведут себя как угодно, но только не становятся как надо.
.menu {
    display: inline;
    align-items: flex-start;
}
.menu-list {
    display: inline;
    font-family: 'Roboto', serif;
    padding-right: 68px;
}
.contacts {
    display: inline;
    align-items: flex-end;
}
.contact-info {
    display: inline-block;
    margin-left: 40px;
}/*текст, выделенный жирным шрифтом*/

Вот html:

BuhOne

ГЛАВНАЯ

УСЛУГИ

КЛИЕНТЫ

О КОМПАНИИ

КОНТАКТЫ

       8 (111) 222-33-44

       Пн-Пт 10:00-18:00

       order@buhone.ru

       Невский пр. 130

Есть лого, она слева, а эти два списка должны быть в правой части сайта.

A:

.menu {
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: flex-end;
  align-items: flex-start;
  align-content: flex-start;
  display: flex;
}

.menu-list {
  display: inline;
  font-family: 'Roboto', serif;
  padding-right: 68px;
}

.contacts {
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: flex-end;
  align-items: flex-start;
  align-content: flex-start;
  display: flex;
  padding-right: 68px;
}

.contact-info {
  display: inline-block;
  margin-left: 40px;
}

BuhOne

ГЛАВНАЯ

УСЛУГИ

КЛИЕНТЫ

О КОМПАНИИ

КОНТАКТЫ

       8 (111) 222-33-44

       Пн-Пт 10:00-18:00

       order@buhone.ru

       Невский пр. 130


text:
Q: How to save a variable value outside of a function in javascript I am newbie to JavaScript, I was trying to make a simple GoogleMaps which is centered in my current position and I am finding problems saving my latitude and longitude to center the map.
Here is my code which i have adopted:
function initialize() {
 var latitudeCenter;
 var longitudeCenter;
 navigator.geolocation.getCurrentPosition(onSuccess, onError);
 function onSuccess(position){
 console.log(position.coords.latitude, position.coords.longitude);
 latitudeCenter = position.coords.latitude;
 longitudeCenter = position.coords.longitude;
 }
 function onError(error){
 alert('Error en GPS: ' + error);
 }
var mapOptions = {
 zoom: 8,
 center: new google.maps.LatLng(latitudeCenter, longitudeCenter)
};
map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);
console.log('latitud: ' + latitudeCenter + ' longitud: ' + longitudeCenter);
}

In the first console log I can read my current position and latitude, so that method works fine, but when I try to save it in centerLatitude and centerLongitude it does not work, it displays undefined.
Thanks for the help

A: So, the functions onSuccess and onError are asynchronous, so you won't get back an answer straight away. So therefore you put your actual map initialisation code inside that onSuccess
function initialize() {
    var latitudeCenter;
    var longitudeCenter;
    navigator.geolocation.getCurrentPosition(onSuccess, onError);

    function onSuccess(position){
        console.log(position.coords.latitude, position.coords.longitude);
        latitudeCenter = position.coords.latitude;
        longitudeCenter = position.coords.longitude;

        var mapOptions = {
            zoom: 8,
            center: new google.maps.LatLng(latitudeCenter, longitudeCenter)
        };

        map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);
    }

    function onError(error){
        alert('Error en GPS: ' + error);
    }

    console.log('latitud: ' + latitudeCenter + ' longitud: ' + longitudeCenter);
}


text:
Q: TypeScript: Argument of type '(error: any) => void' is not assignable to parameter of type Following Code:
private getJSON(): Observable<any> {
    return this.http.get('./reportNav-NEW.json')
      .map((res:any)=> res.json())
      .catch((error:any) => console.log(error));
  }

The Error gives me:

Argument of type '(error: any) => void' is not assignable to parameter
  of type '(err: any, caught: Observable) => ObservableInput<{}>'.
  Type 'void' is not assignable to type 'ObservableInput<{}>'.

It happens in the .catch((error:any) => console.log(error));

A: This worked for me (thanks to @trevor in the comments)
private getJSON(): Observable<any> {
    console.log(document.location.href);
    return this.http.get('...')
      .map((res:any)=> res.json())
      .catch((error:any) => {
        return Observable.throw(error);
      })
  }

update: Now with rxjs 6 you have to call "throwError" operator from "rxjs/operators", and use it instead of "Observable.throw".


text:
Q: Android: 2.1 AND install on SD-card feature for 2.2+ users I want my Android application to support 2.1 (Eclair), but I also want it to support installation to sd-card for 2.2 (and later) users.
I'm using MOTODEV, and I created a new 2.1 project. I tried adding    android:installLocation="preferExternal" to my manifest file, but it doesn't work because it's not supported in 2.1. How can i make my application support SD-installation and at the same time support 2.1?
EDIT: I see I can use android:installLocation="preferExternal" even for 2.1 and older builds according to http://developer.android.com/guide/appendix/install-location.html#Compatiblity. The trick is, as CommonsWare stated below, to change the build target to 2.2.
The problem now is that Eclipse/Motodev won't let me run or debug on virtual devices that are older than the build. It simply doesn't list the device. I tried tricking it by changing the build target, choosing an older device in run/debug configurations, and then changing build target back, but I just got the following message in the console:
Preferred AVD 'eclair_hvga' is not compatible with the project target 'Android 2.2'. Looking for a compatible AVD...

A: Set your build target (Android section of project properties in MOTODEV Studio for Android) to 2.2. This causes you to use 2.2 rules for compilation, and android:installLocation should be recognized. Then, test your app on 2.1 and 2.2.

A: So is this bug in eclipse ? When you set build target to higher version then android:minSdkVersion it wont allow you to run on minSdkVersion. This answer is incorrectly  accepted, when it don't work in Eclipse (that was in question).


text:
Q: Capture only the file name from the directory Path Requirement
Col1 ,  Col2             ,         Col3         ,   Col4
1   , a:/b/c/abc.txt          , f:/b/c/abc1.txt , a:/b/c/abc6.txt
2   , b:/bd/a/s/3/d/mon.dat   , g:/b/c/abc 2.txt, b:/b/c/ab7.txt
3   , c:/j/h/4/u/y/d/m/ttt.dat, h:/b/c/abc 3.txt, c:/b/c/abc 8.txt
4   , c:/j/h/4/test1.msg      , i:/b/c/abc4.txt , d:/b/c/abc 9.txt
5   , d:/iasa/dda/dia/yyy.dat , j:/b/c/abc5.txt , e:/b/c/abc 10.txt

Expecte O/P
Col1  ,    Col2     ,    Col3    ,   Col4
1  ,       abc.txt   ,   abc1.txt ,  abc6.txt
2  ,       mon.dat   ,   abc2.txt  , abc7.txt
3  ,       ttt.dat   ,   abc3.txt  , abc8.txt
4  ,       test1.msg ,   abc4.txt  , abc9.txt
5  ,       yyy.dat   ,   abc5.txt  , abc10.txt

A: As I couldn't infer any system in the space distribution, I just guessed some formatting. Feel free to adapt to taste.
awk -F, '{gsub (/ |\r/, ""); printf "%-4s ", $1; for (i=2; i<=NF; i++) {n=split($i, T, "/"); printf ", %-10s ", T[n]} printf RS}' OFS=, file
Col1 , Col2       , Col3       , Col4
1    , abc.txt    , abc1.txt   , abc6.txt
2    , mon.dat    , abc2.txt   , ab7.txt
3    , ttt.dat    , abc3.txt   , abc8.txt
4    , test1.msg  , abc4.txt   , abc9.txt
5    , yyy.dat    , abc5.txt   , abc10.txt

A: Using sed and column:
$ sed 's/ //g; s/,[^,]*\//,/g; s/,/ , /g' file | column -t
Col1  ,  Col2       ,  Col3      ,  Col4
1     ,  abc.txt    ,  abc1.txt  ,  abc6.txt
2     ,  mon.dat    ,  abc2.txt  ,  ab7.txt
3     ,  ttt.dat    ,  abc3.txt  ,  abc8.txt
4     ,  test1.msg  ,  abc4.txt  ,  abc9.txt
5     ,  yyy.dat    ,  abc5.txt  ,  abc10.txt

*

*replace all space characters with an empty string

*replace all , followed by non-, characters followed by / with a ,

*replace all , with  ,

*pretty print the output as table with column


text:
Q: Accessing exported gcode from Slic3r? I've been using Ubuntu for about a month and am definitely a novice, apologies if this question is trivial.
I use a program called Slic3r to create gcode (machine instructions) from stl files for 3D printing. Slic3r is supported in linux, but exports gcode to a directory called:
home/artemis/.local/share/Repetierhost
I can't seem to locate this directory in linux like I could in Windows. "Artemis" is my username.
If someone could give me a hand locating the exported gcode and perhaps making a link to the directory where new gcode is exported that would be excellent.
Am definitely enjoying the Ubuntu experience thus far too.

A: Files an folders that has names starting with "." are hidden. They are normally not displayed. To see them there is a command in menu.

A: In Linux, all files starting with a dot are hidden files.
If you want to show hidden files in a terminal, use ll instead of ls
If you want to show hidden files in your file manager press "View" and then "Hidden files" (Or press Ctrl+H)
Alternatively, you can create a shortcut to the "Repetierhost" directory by right-clicking it, clicking "make link" and then moving the "Link To Repetierhost" to your desktop...


text:
Q: Is "when" a conjunction in "I'll believe it when I see it." I'm asking this question because if I remove the word "when" I get two sentences that can stand on their own 1. I'll believe it. 2. I see it.
I suppose in such cases "when" functions as a conjunction. I'm not exactly sure, though. Any suggestion is appreciated.

A: Correct, "when" is indeed a conjunction in your example because it connects two related ideas.
In fact, "when" is used as a conjunction rather often and in a variety of circumstances. Have a look at its entry in the Oxford Dictionary for more definitions and examples.

A: I'll believe it when I see it.
You are right; the word "when" is a conjunction. There are two clauses i.e. the main clause "I'll see it" and the subordinate or dependent clause introduced by when "when l see it".  The subordinate conjunction when  joins the two clauses.


text:
Q: Vim :e starting directory? I code in Vim, not an IDE.
My source code is often nested 2-3 directories deep.
~/foo$ find
xyz
bar/abc
bar/def

~/foo$ vim
// inside of vim
:e bar/abc
... some work ...
:e <-- is there a way I can have this :e start in ~/foo/bar instead of ~/foo ?

Basically, I want :e to start the directory in "pathname of last edited file"
Thanks!

A: To always change the working directory to the current file's directory I have this in my .vimrc:
if has("autocmd")
  autocmd BufEnter * :lcd %:p:h
endif " has("autocmd")

A: Sorry, but vim's :edit command takes a path which is interpreted relative to the present working directory of the vim instance.
You do have a :cd command which you could use to :cd bar then work for a while, then :cd ...
Hope that help some.

A: There's a lot of reasons not to like autochdir as it messes up some plugins and if you end up doing :e ../../../foo.txt you are not gaining anything. Just as an idea try this cmap I knocked up
:cnoremap red edit <c-r>=expand("%:h")<cr>/

then you can type :red and get
:e /the/path/to/your/current/files/dir/

(edit: perhaps use z instead of red as there are commands that start with red)
To expand the topic, also check out the FuzzyFinder plugin and some custom mappings to rapidly jump to common files you are always editing. Eg
10 or so of your regular files should be no more than 2 keystrokes away. It helps if they are systematically named
Here's an idea I use for django.
http://code.djangoproject.com/wiki/UsingVimWithDjango#Mappings

A: Try the autochdir option. It will automatically change the current working directory to whatever file was most recently opened or selected. In .vimrc:
set autochdir

For more info, :help autochdir

A: Some time ago I asked questions related to this on the vim mailing list: http://www.mail-archive.com/vim_use@googlegroups.com/msg03266.html Maybe you will find useful tips in that thread.
I tested a lot of plugins, but since CLI based GUIs are not my taste, I simply ended up using standard vim with a few configuration settings.
As honk pointed out, this line sets the working directory to the same as the file your working on:
autocmd BufEnter * lcd %:p:h

My other tip is to use the wildmenu. It makes it easier to get an overview of the files in your current directory when you go :e and then TAB. I'm a python programmer so the last line shows how to hide auto generated files that the python interpreter spits out, but you could use it to hide java .class files or c .obj files or whatever.
set wildmode=list:longest
set wildignore=*.pyc,*pyo

A: *

*:cd changes directory

*:pwd prints the current one.

A: why not just :E? Explore directory of current file.
:help :E

A: This isn't exactly what you wanted, but check out NERDTree.

A: On vim/gVim I just have cd C:/blah/blah at the top of my vimrc. I imagine it works on all platforms.
I personally use vagrant for each project so one CD is enough, but I think you can get vim to use different config files too, -u flag I think.
Or map a key to each project you have so pressing Ctrl+F1 does cd path/to/project/1 and Ctrl+F2 does cd path/to/project/2 perhaps?
Note: I don't use any plugins


text:
Q: User information get lost after refreshing the page (Firebase + React) I am trying to create a Navigation bar. When the user is not logged in, they see a Navigation bar, with the title of the page only. Once the user logs in, he should see the title, other pages, his email address, and a logout button.
I can retrieve the email address, but when I refresh the page and click the logout button I get an error saying:
TypeError: Cannot read property 'email' of null
I am attaching my code for the navigation bar and how I can it in app.js, down below.
I am not sure how can I tackle this problem.
NavigationBar.js:
const NavigationBar = ({ authUser }) => (

{authUser ? <NavigationBarAuth /> : <NavigationBarNonAuth />}

);

const NavigationBarAuth =()=>{
    return (
         ...
         <Grid item xs={3}>

               {fire.auth().currentUser.email}

         </Grid>
    );

App.js:
 constructor(props) {
    super(props);

    this.state = {
      authUser: null,
      // authUser: JSON.parse(localStorage.getItem('authUser')),
    };
  }
  componentDidMount() {
    this.listener = fire.auth().onAuthStateChanged(
      authUser => {
        authUser
          ? this.setState({ authUser })
          : this.setState({ authUser: null });
      },
    );
  }
 componentWillUnmount() {
    this.listener();
  }
  render() {
    return (
            ...
            <NavigationBar authUser={this.state.authUser} />
    );
  }

A: After debugging, I understood the problem was somewhere else. I had a Signout function and called the function in button onClick. I called the function wrongly which is why the signout function got fired and nullified the user.
Thanks for your help and effort.


text:
Q: Error when extracting comments in my facebook page through laravel app using Facebook graph API I'm trying to extract comments in my facebook page. For that I made a Facebook graph app. I can extract the comments in Graph API explorer using {page-id}?fields=posts.limit(1000){comments} query.
But when I tried to get comments through a laravel app, it gives me an error. The code in laravel app is
$fb = new Facebook([
        'app_id' => getenv('FACEBOOK_APP_ID'),
        'app_secret' => getenv('FACEBOOK_APP_SECRET'),
        'access_token'    => getenv('FACEBOOK_ACCESS_TOKEN'),
        'default_graph_version' => 'v3.3',
        ]);

        $accessToken=getenv('FACEBOOK_ACCESS_TOKEN');
    try {

        $response = $fb->get('/{page-id}?fields=posts.limit(1000){comments}',$accessToken);

      } catch(Facebook\Exceptions\FacebookResponseExcepti9on $e) {
        $e->getMessage();
        exit;
      } catch(Facebook\Exceptions\FacebookSDKException $e) {
        // echo 'Facebook SDK returned an error: ' . $e->getMessage();
        $e->getMessage();
        exit;
      }
      $graphNode = $response->getGraphNode();

Error is

(#10) To use 'Page Public Content Access', your use of this endpoint must be reviewed and approved by Facebook. To submit this 'Page Public Content Access' feature for review please read our documentation on reviewable features: https://developers.facebook.com/docs/apps/review.

This is how my graph permission and features page looks. What am I doing wrong?


text:
Q: Buttons Don't Initially Draw I'm having an issue with my applet where the buttons do not draw until you mouse over them. They stay after that, but once you click one, they go away again. Here is my code:
    checkPanel = new JPanel();

    buttonPanel = new JPanel();
    buttonPanel.setLayout( new GridLayout( 1, 7 ) );

    openAdvancedSettings = new JButton( "Advanced Settings" );
    openAdvancedSettings.addActionListener( this );

    checkPanel = new JPanel();
    checkvolt = new Checkbox( "Voltage", true );
    checkv = new Checkbox( "v gate", false );
    checkw = new Checkbox( "w gate", false );
    checks = new Checkbox( "s gate", false );

    checkvolt.addItemListener( this );
    checkv.addItemListener( this );
    checkw.addItemListener( this );
    checks.addItemListener( this );

    checkPanel.setLayout( new GridLayout( 20, 8 ) );
    checkPanel.add( butp );
    checkPanel.add( prompt0 );
    checkPanel.add( checkvolt );
    checkPanel.add( prompt1 );

    butt = new JButton( "Start" );
    butt.addActionListener( this );
    buttonPanel.add( butt );

    setLayout( new BorderLayout() );
    add( checkPanel, BorderLayout.EAST );
    add( buttonPanel, BorderLayout.NORTH );
    add( openAdvancedSettings, BorderLayout.SOUTH );

The first 2 adds are JPanels, and the last one is a JButton. Most of the buttons (all but the last one) are in those 2 panels.
I have also come to the conclusion that the method repaint() is causing this to happen. What am I doing wrong?

A: I am assuming in the absence of a good SSCCE, that you must have failed to put your code, that is responsible for creating and displaying your GUI, for attaining Concurrency in Swing, inside SwingUtilities.invokeLater(...);
Secondly, you can try calling revalidate() method, on your panel, before calling repaint(). That might can solve the problem for the time being.
Hope that might help in some way.
Regards

A: *

*Don't mix Swing (e.g. JPanel) & AWT (e.g. CheckBox) components.  Comment out any AWT import(s) and check that only layouts are missing.

*Ensure that validate() is called after all components are added.

*And as Gagandeep Bali advised:-  Construct the GUI on the EDT, and post an SSCCE if you cannot get it sorted.


text:
Q: Implement WCF Data Service using the Repository Pattern We are using the repository pattern in our ASP.NET MVC 3 application. This means that, although we use EF 4.1 Code First to access the data in the backend, all MVC controllers do that via a generic repository class rather than directly over the DbContext subclass.
Simplified code snippet:
public class MyEntityContext : DbContext, IMyEntityContext
{
    public IDbSet MyEntities { get; set; }
    ...
}

public class MyEntityRepository : IMyEntityRepository
{
    private IMyEntityContext _context;

    public IQueryable<MyEntity> MyEntities
    {
        return _context.MyEntities;
    }
    ...
}

public class MyEntityController : Controller
{
    private MyEntityRepository _repository;
    ...
}

We use interfaces and dependency injection for every dependency. It works fine. Looks nice, doesn't it? But now for the caveat:
We also provide a WCF Data Service (CTP supporting Code First) to access the entities. We want to use the repository in that service, too. But this seems tricky. When using the MyEntityContext directly, the service looks like this:
public class MyEntityService : DataService<MyEntityContext>
{
    public static void InitializeService(DataServiceConfiguration config)
    {
        config.SetEntitySetAccessRule("MyEntities", EntitySetRights.All);
    }
}

But when I try to replace the MyEntityContext by the repository, there are two issues:

*

*The type specified for the generic DataService<..> needs to be a class with a default constructor, which breaks the pretty design-by-contract and dependency injection design.

*It even seems that the type provided has to be a DbContext class: I tried and used the MyEntityRepository instead, but failed (see details).

I seem lost... Can anyone bring me back on the proper track?

Details:
My first go was:
public class MyEntityService : DataService<MyEntityRepository>
{
    ...

However, when calling the service, it fails with the following error message:

The server encountered an error processing the request. The exception message is 'On data context type 'MyEntityRepository', there is a top IQueryable property 'MyEntities' whose element type is not an entity type. Make sure that the IQueryable property is of entity type or specify the IgnoreProperties attribute on the data context type to ignore this property.'.

I tried the following steps to fix this, but did not get rid of this error message:

*

*Adding a [DataServiceKey("MyEntityId")] to MyEntity, where MyEntityId is the correct key property of the entity.

*Replacing the type of Repository.MyEntities by IDbSet instead of IQueryable.

BTW: The following posts are not duplicates:

*

*WCF Repository Service pattern with entity framework

*Service Layer/Repository Pattern

*Best way to implement Repository Pattern?

*webservices with repository pattern in c# and WCF?

*WCF Service design pattern

A: Why do you want to use repository? You have context so use it. Don't create onion architecture just because you want to use pattern. WCF data service already handles everything you need itself. No sorry, it sometimes offers even more (for example interceptors).
By using custom repository you are moving to reflection provider data source. If you also plan to modify your entities through WCF data service that is also against your repository because reflection provider is read only unless it also implements IUpdateable. Check also rules for reflection provider.
Btw. WCF Data Services in .NET 4 doesn't support DbContext directly (that support is only in CTPs of upcoming version) but you there is workaround for that. The link is for old CTP. In current version there is not UnderlyingContext property but you can use IObjectContextAdapter to get ObjectContext.
As you can also see in last link type provided to the service doesn't need to have default constructor - it is up to you what constructor you use when creating data source. If you need dependency injection you will probably have to check the way how to inject directly to the service itself (for example here for Unity and plain WCF) and use injected data in CreateDataSource.

A: Here's how to make a WCF Data Service with whatever pattern you're using, even none at all.
Getting Started With OData Part 2: Building an OData Services from Any Data Source
Just make sure your entity, poco, model or whatever has a property public int ID , or has this class annotation provided by the System.Data.Services assembly in the System.Data.Services namespace:
[DataServiceKey("TheNameOfYourPrimaryKeyProperty")]

This will make it recognizable as an entity type by the WCF Data Service.
As others have pointed out though, just make sure that adding yet another layer in your stack is a good decision.


text:
Q: @discordjs/opus Cannot create a Buffer larger than 0x100000000 bytes Я пытаюсь записать и воспроизвести разговор человека в голосовом канале Discord. Бот подключается к каналу по slash-команде и слушает вызвавшего его пользователя. Звук передаётся в кодеке Opus и приходит в виде чанков stream.on('data', (chunk) => {}), после чего декодируется и добавляется к предыдущему чанку.
Однако, при попытке кодировать весь звук, переданный за разговор, в строке connection.playOpusPacket(encoder.encode(phrase)) возникает ошибка

Cannot create a Buffer larger than 0x100000000 bytes

Код приёма и кодировки:
const { Client, Intents } = require('discord.js');
const { OpusEncoder } = require('@discordjs/opus');
const { joinVoiceChannel } = require('@discordjs/voice');
const { VoiceConnectionStatus } = require('@discordjs/voice');

const client = new Client({ intents: [Intents.FLAGS.GUILDS, "GUILD_VOICE_STATES"] }); // создаём Discod-клиент

//... добавление slash-команд

// когда использована slash-команда
client.on('interactionCreate', async interaction => {
if (!interaction.isCommand()) return;

const connection = joinVoiceChannel({ // подключаемся к голосовому каналу
    channelId: interaction.member.voice.channel.id,
    guildId: interaction.member.voice.channel.guild.id,
    adapterCreator: interaction.member.voice.channel.guild.voiceAdapterCreator,
});
connection.on(VoiceConnectionStatus.Ready, () => {
    const receiver = connection.receiver;
    const stream = receiver.subscribe(interaction.member.id); // подписываемся на прослушку пользователя
    let startSpeak = false;
    let phrase = new Uint8Array();
    const encoder = new OpusEncoder(48000, 1); // создаём Opus encoder/decoder

    stream.on('data', (chunk) => { // когда пользователь говорит
                    if (!startSpeak){
                         console.log("Start speaking");
                         startSpeak = true;
                    }
                    let oldPhrase = phrase;
                    let decoded = encoder.decode(chunk); // декодируем Opus чанк
                    phrase = new Uint8Array(oldPhrase.length + decoded.length); // создаём новый массив с длинной старых чанков и нового
                    phrase.set(oldPhrase); // записываем старые чанки
                    phrase.set(decoded, oldPhrase.length); // записываем новый чанк
                });

    connection.receiver.speaking.on('end', () => { // когда пользователь закончил говорить
                    console.log("ended");
                    startSpeak = false;
                    connection.playOpusPacket(encoder.encode(phrase)); // кодируем чанки и проигрываем в Discord
                    phrase = new Uint8Array(); // очищаем массив чанков
                })
});

});
client.login(токен бота);


text:
Q: how to validate a struct field of type null.v4 package with validator v10? I have a struct that i'm trying to validate a struct using validator v10 for which field can be of type null.XX from null.v4 package.
type FooStruct struct {
    Foo null.Int `json:"foo" binding:"nullIntMin=1"`
}

it's (obviously ) not working out of the box so i'm trying to make a custom validator.
var validateNullIntMin validator.Func = func(fl validator.FieldLevel) bool {
    number, ok := fl.Field().Interface().(null.Int)
    min := cToInt(fl.Param())
    if ok {
        if number.Value > min && number.Valid {
            return false
        }
    }
    return true
}

func cToInt(param string) int64 {

    i, err := strconv.ParseInt(param, 0, 64)
    panic(err)

    return i
}

The problem is that the data is never validated. Is never even entering the function and i can't understand why.
example to reproduce :
package main

import (
    "log"
    "net/http"
    "strconv"

    "github.com/gin-gonic/gin"
    "github.com/gin-gonic/gin/binding"
    "github.com/go-playground/validator"
    "gopkg.in/guregu/null.v4"
)

type FooStruct struct {
    Foo null.Int `json:"foo" binding:"nullIntMin=3"`
}

var validateNullIntMin validator.Func = func(fl validator.FieldLevel) bool {
    log.Println("inside validator")
    number, ok := fl.Field().Interface().(null.Int)
    min := cToInt(fl.Param())
    if ok {
        if number.Valid && number.Int64 > min {
            return false
        }
    }
    return true
}

func cToInt(param string) int64 {

    i, err := strconv.ParseInt(param, 0, 64)
    panic(err)

    return i
}

func main() {
    route := gin.Default()

    // Custom validator

    if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
        v.RegisterValidation("nullIntMin", validateNullIntMin)
    }

    route.POST("/foo", postFoo)
    route.Run(":5000")
}

func postFoo(c *gin.Context) {
    var f FooStruct
    err := c.BindJSON(&f)
    if err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"status": http.StatusText(http.StatusBadRequest)})
        return
    }
    c.JSON(http.StatusOK, gin.H{"status": http.StatusText(http.StatusOK), "data": f.Foo.Int64})

}

if you call it with
{"foo":1}

you'll get  {
"data": 1,
"status": "OK"
}
when i'm expecting Error:Field validation for 'Foo' failed on the 'nullIntMin' tag

A: You dont need to unparse the field inside the validator and make a custom case just for the special type.
Instead just create a new type then you can just use the normal bindings.
if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
    v.RegisterCustomTypeFunc(nullIntValidator, null.Int{})
}

func nullIntValidator(field reflect.Value) interface{} {
    if valuer, ok := field.Interface().(null.Int); ok {
        if valuer.Valid {
            return valuer.Int64
        }
    }
    return nil
}

type FooStruct struct {
    Foo  null.Int  `json:"foo" binding:"min=3"`
}


text:
Q: urllib.error.HTTPError: HTTP Error 503: Service Unavailable - Web Crawler I'm very new to stack overflow and even newer yet to coding. I made this web crawler from a bit of this and that I've found over a multitude of web searches. My intention is to take a keyword input and search it on google crawling through each page and returning email addresses into a csv file. It worked just yesterday now i'm getting this error 503 error. Can anyone please show me how to overcome this? Here is my code.
import logging
import os
import pandas as pd
import re
import scrapy
import time

from scrapy.crawler import CrawlerProcess
from scrapy.linkextractors.lxmlhtml import LxmlLinkExtractor
from googlesearch import search

def get_urls(tag, n, language):
    urls = [url for url in search(tag, stop=n, lang=language)][:n]
    time.sleep(2)
    return urls

class MailSpider(scrapy.Spider):

    name = 'email'

    def parse(self, response):

        links = LxmlLinkExtractor(allow=()).extract_links(response)
        links = [str(link.url) for link in links]
        links.append(str(response.url))

        for link in links:
            yield scrapy.Request(url=link, callback=self.parse_link)

    def parse_link(self, response):

        for word in self.reject:
            if word in str(response.url):
                return

        html_text = str(response.text)
        mail_list = re.findall('\w+@\w+\.{1}\w+', html_text)

        dic = {'email': mail_list, 'link': str(response.url)}
        df = pd.DataFrame(dic)

        df.to_csv(self.path, mode='a', header=False)
        df.to_csv(self.path, mode='a', header=False)

def ask_user(question):
    response = input(question + ' y/n' + '\n')
    if response == 'y':
        return True
    else:
        return False

def create_file(path):
    response = False
    if os.path.exists(path):
        response = ask_user('File already exists, replace?')
        if response == False: return

    with open(path, 'wb') as file:
        file.close()

def get_info(tag, n, language, path, reject=[]):

    create_file(path)
    df = pd.DataFrame(columns=['email', 'link'], index=[0])
    df.to_csv(path, mode='w', header=True)

    print('Collecting Google urls...')
    google_urls = get_urls(tag, n, language)

    print('Searching for emails...')
    process = CrawlerProcess({'USER_AGENT': 'Mozilla/5.0'})
    process.crawl(MailSpider, start_urls=google_urls, path=path, reject=reject)
    process.start()

    print('Cleaning emails...')
    df = pd.read_csv(path, index_col=0)
    df.columns = ['email', 'link']
    df = df.drop_duplicates(subset='email')
    df = df.reset_index(drop=True)
    df.to_csv(path, mode='w', header=True)

    return df

bad_words = ['facebook', 'instagram', 'youtube', 'twitter', 'wiki']
df = get_info(input('What keywords would you like to collect emails for?:'), int(input('How many Websites would you like to crawl?')), 'pt', input('Enter a name for csv file:')+'.csv', reject=bad_words)

df.head()

A: So I don't know if this makes a difference but I logged into my other google account and it started working again.


text:
Q: AWS CLI Errno 13 Permission Denied, cannot set credentials using aws configure command first time question so please excuse my poor question formatting. I'm running up to date(enough) Python, AWS CLI v2, installed with MSI, config and credentials file both have values, no environment variables set, Windows 10, using Command Prompt.
When I input:
C:\Users\correctuser> aws --version

This is what returns:
aws-cli/2.5.2 Python/3.9.11 Windows/10 exe/AMD64 prompt/off

When I type:
C:\Users\correctuser> aws configure list

This is what I get:
      Name                    Value             Type    Location
      ----                    -----             ----    --------
   profile                <not set>             None    None
access_key                <not set>             None    None
secret_key                <not set>             None    None
    region                us-west-2      config-file    ~/.aws/config

//I have both regular and secret access keys set in the 'credentials' file in C:\users\correctuser.aws\credentials, and the region and format set in C:\users\correctuser.aws\config.
[default]
region = us-west-2
output = json

[default]
aws_access_key_id = thisisfakeaccesskeyID
aws_secret_access_key = thisisfakesecretaccesskeyID

And then when I type:
C:\Users\GitUser>aws configure
AWS Access Key ID [None]: thisisfakeaccesskeyID
AWS Secret Access Key [None]: thisisfakesecretaccesskeyID
Default region name [us-west-2]:
Default output format [json]:

[Errno 13] Permission denied: 'c:\\users\\GitUser\\.aws'

I heard that sometimes when your file name doesn't have a backslash at the end of it that can cause an error, though I don't think that's what it is. I've also tried running Command Prompt as administrator and that didn't help.
What do y'all think?

A: To fix the problem you have to give write permission to the file.
If you run on unix/OSX
// Set permission
sudo chmod -R 777 /{Your_Path}/.aws/credentials
sudo chmod -R 777 /{Your_Path}/.aws/config

Windows
1:- Right-click on the target file and select properties then select Security Tab
2:- Click Advanced and then make sure inheritance is disabled.
3:- Click apply and then click Edit in the security menu
4:- Remove all users except Admin user, which should have full control *Admin account should have all checkboxes checked on Allow column except special permission.
5:- Click Apply and then click OK.

A: I first tried to give the permissions but also that did not fix the error at first.
When I checked the location the config.ini and credentials.ini did not exist.
After creating the files by editing a text file and saving it as the .ini files.
The error disappeared from that moment.


text:
Q: How to set the minimum value for time difference? If the time difference between departure time and arrival time is less than less than 30 minutes or negative, how to assume the value to be 30 ?
For example, I have the following datatype:
id         departure time             arrival time         start  end  capacity

Train A   2016-05-19 01:45:00       2016-05-19 08:25:00   A     G    2
Train A   2016-05-19 16:54:00       2016-05-19 16:00:00   B     H    2
Train A   2016-05-19 21:25:00       2016-05-20 07:25:00   C     I    3
Train B   2016-05-24 02:20:00       2016-05-24 12:50:00   D     J    3
Train B   2016-05-24 18:30:00       2016-05-25 20:00:00   E     K    2
Train B   2016-05-26 19:35:00       2016-05-26 19:45:00   F     L    3

I use the following formula to find the time difference
df['time difference'] = ((df['departure time'] - df['arrival time']).abs())

I want to set the minimum value of time difference to be 30, )if the value is less than 30 or negative)

A: You can subtract columns and convert to minutes by total_seconds and divide 60 first and then replace to 30 by mask:
diff = (df['departure time'] - df['arrival time']).dt.total_seconds() / 60
df['time difference'] = diff.mask(diff < 30, 30)
print (df)
        id      departure time        arrival time start end  capacity  \
0  Train A 2016-05-19 01:45:00 2016-05-19 08:25:00     A   G         2
1  Train A 2016-05-19 16:54:00 2016-05-19 16:00:00     B   H         2
2  Train A 2016-05-19 21:25:00 2016-05-20 07:25:00     C   I         3
3  Train B 2016-05-24 02:20:00 2016-05-24 12:50:00     D   J         3
4  Train B 2016-05-24 18:30:00 2016-05-25 20:00:00     E   K         2
5  Train B 2016-05-26 19:35:00 2016-05-26 19:45:00     F   L         3

   time difference
0             30.0
1             54.0
2             30.0
3             30.0
4             30.0
5             30.0


text:
Q: Copy only newer files from one server to another server I have a Build server and i would like to copy the newest deployment file from that location to another location on remote server using MSBuild but i am stuck on doing this as well as confused.
So in my build output directory i have a files such as this:
Installer - 2.5.1403.1201.msi
Installer - 2.5.1405.0701.msi
Now i want to copy the newest file Installer - 2.5.1405.0701.msi to remote server called ServerB.
I read that using PSExec shouldn't be used for copy files from build server to another server. Is there a reason why?
Currently i have the following code but i only got it to work locally on my machine:
 <ItemGroup>
   <File Include="C:\\LocalCopy\\Installer - 2.5.1403.1201.msi" />
</ItemGroup>
<PropertyGroup>
  <DestinationFolder>C:\\Dump</DestinationFolder>
</PropertyGroup>
 <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
 <Target Name="AfterBuild" Inputs="@(File)" Outputs="@(File -> '$(DestinationFolder)\% (RelativeDir)%(Filename)%(Extension)')">
    <Copy SourceFiles="@(File)" DestinationFolder="$(DestinationFolder)" />
 </Target>

Can someone provide me with advice how i could go about doing this?
Thanks & Regards,


text:
Q: Python can't print variable in batch language I want to print batch variable using echo in python.
from os import system

def CMD(cmd): # this is for do many stuff in one function
    for a in range(0, len(cmd)):
        system(cmd[a])

CMD(["ECHO Hello World!",
     "SET var=Hi!",
     "ECHO %var%", # here i want to print "Hi!" but it prints %var%
     "PAUSE"])

Output:
%var% # i want to get variable: "Hi!"

How do I success this?


text:
Q: ggplot: how to add an outline around each fill in a stacked barchart but only partly I have the following stacked barchart produced with geom_bar.
Question: how to add an outline around each fill corresponding to the matched color in cols. The tricky part is, that the outline should not be in between each fill but around the "borders" and the top, exclusively (expected output below)
I have

Written with
library(ggplot)
cols = c("#E1B930", "#2C77BF","#E38072","#6DBCC3", "grey40","black")

ggplot(i, aes(fill=uicc, x=n)) + theme_bw() +

  geom_bar(position="stack", stat="count") +

  scale_fill_manual(values=alpha(cols,0.5))

Expected output

My data i
i <- structure(list(uicc = structure(c(4L, 4L, 4L, 4L, 3L, 4L, 4L,
4L, 4L, 3L, 4L, 3L, 4L, 2L, 4L, 4L, 4L, 1L, 4L, 4L, 2L, 4L, 4L,
3L, 4L, 4L, 4L, 4L, 3L, 2L, 4L, 4L, 3L, 3L, 3L, 3L, 1L, 3L, 4L,
4L, 2L, 4L, 4L, 4L, 4L, 4L, 4L, 1L, 4L, 4L, 4L, 4L, 4L, 4L, 3L,
4L, 1L, 3L, 1L, 4L, 4L, 3L, 1L, 2L, 1L, 3L, 3L, 3L, 4L, 3L, 4L,
4L, 3L, 4L, 3L, 3L, 3L, 2L, 2L, 4L, 3L, 4L, 2L, 1L, 1L, 4L, 4L,
4L, 4L, 1L, 4L, 4L, 4L, 4L, 4L, 4L, 2L, 3L, 3L, 4L), .Label = c("1",
"2", "3", "4"), class = "factor"), n = structure(c(4L, 4L, 4L,
4L, 2L, 1L, 4L, 1L, 4L, 2L, 4L, 2L, 4L, 1L, 4L, 5L, 2L, 1L, 1L,
5L, 1L, 1L, 2L, 2L, 1L, 4L, 3L, 4L, 2L, 1L, 5L, 2L, 2L, 2L, 2L,
2L, 1L, 2L, 3L, 2L, 1L, 4L, 2L, 1L, 4L, 1L, 4L, 1L, 2L, 2L, 2L,
4L, 1L, 4L, 2L, 4L, 1L, 1L, 1L, 4L, 1L, 2L, 1L, 1L, 1L, 2L, 2L,
1L, 1L, 2L, 4L, 1L, 1L, 4L, 2L, 2L, 2L, 1L, 1L, 3L, 2L, 5L, 1L,
1L, 1L, 4L, 4L, 4L, 5L, 1L, 4L, 4L, 1L, 4L, 2L, 1L, 1L, 2L, 2L,
4L), .Label = c("0", "1", "2", "3", "4", "5"), class = "factor")), row.names = c(NA,
100L), class = "data.frame")

A: Well, I found a way.
There's no easy way to draw just the "outside" lines, so the approach I used was to go ahead and draw them with the geom_bar call.  The inner lines are "erased" by drawing white rectangles over top the initial geom_bar call, and then the fill is drawn back in with a colorless color= aesthetic.
In order to draw the rectangles over the initial geom_bar call, I created a summary dataframe of i which sets the y values.
i.sum <- i %>% group_by(n) %>% tally()

ggplot(i, aes(x=n)) + theme_bw() +

  # draw lines
  geom_bar(position='stack', stat='count',
      aes(color=uicc), fill=NA, size=1.5) +

  # cover over those inner lines
  geom_col(data=i.sum, aes(y=nn), fill='white') +

  # put back in the fill
  geom_bar(position='stack', stat='count',
      aes(fill=uicc), color=NA) +

  scale_fill_manual(values=alpha(cols,0.5)) +
  scale_color_manual(values=cols)

Note that the size= of the color= aesthetic needs to be much higher than normal, since the white rectangle ends up covering about half the line.


text:
Q: Regarding precision and recall for the highly unbalanced validation data set
Possible Duplicate:
Optimising for Precision-Recall curves under class imbalance

I built a classification model and tested it against a validation data set. The positive set is composed of 86 cases and the negative set is composed of 1256 cases. The confusion matrix is as follows
                     True positive  True negative   precision
   Predict positive    55               338          13.99%
   Predict negative    31               918          96.73%
           Recall      63.95%       73.09%

The precision and recall for this classifier is not good, especially for the positive precision. However, the negative cases are much more than the positive case. I am not quite sure that,  for  this kind of unbalanced data, can we still use the precision and recall as the performance evaluation as usual?

A: I work in biomedical text classification, where this sort of situation happens all the time. You're exactly right--precision and recall aren't all that informative for highly-skewed data. I tend to use AUC as my performance metric, as it's not sensitive to class distribution.

A: You could introduce a cost function, consistent with your application,  with values for TP, FP, TN, FN  and optimise your predictors for that.

A: I think you need to be clearer what you mean when you say "Not valid": in the sense that they summarise the contingency table, they are valid, but they are biased in the case of highly imbalanced data. One alternate measure you can look at, which tends to be more stable across class balance, is the mean of true positive rate and (1 - false positive rate).
You should be careful about what you want to do with this, though: precision on your positive class is a useful metric to have, because optimising that recall/precision tradeoff on an infrequently occurring class is often the goal of the practical application of classifiers.


text:
Q: How to export labels from QGIS to CAD? When using the export function via Project -> Import/Export my labels do not appear in CAD afterwards. I checked the "Export as MTEXT" box and tried using different scales. But I cannot get the labels to be exported to the dxf-file. The polygons and lines are being exported just fine. Only the labels are missing.
I'm working with QGIS 3.10.4 and open my dxf-files with AutoCAD LT 2019.
Anyone an idea what might be wrong or how I can get my labels to CAD?

A: I found the solution myself:
In the layer properties the size of the labels mustn't be in "Meters at Scale". I can't get it to work, no matter what settings I use.
It works fine with "Map Units", no matter the scale you choose in the export window.
When using "Millimeters", "Points", "Pixels" or "Inches" you have to set the Symboloby scale in the export window to the exact scale you are currently viewing in your map. E.g. if you're currently on a scale of 1:4105 in your map view, you'll have to set exactly this scale in the export window for the labels to be exported.

A: Important is the Export labels as MTEXT elements. It will impact your edits in AutoCAD when the Select Similar option is selected.
With MTEXT - you cannot apply the defined font style to your items! So if you wish to change the font style (other than .shx -shaped) then it's good to export your layer without MTEXT.
On the other hand, by exporting with MTEXT you will be able to set the font background and label.

It's good to know the further font circumstances generated by these 2 ways of DXF export.

A: The Scale factor for Symbology needs to be set:
1:1,000 works for this example.


text:
Q: Kubuntu: Second monitor not detected correctly After a recent update, my second monitor is not detected correctly anymore. It is displays a copy of the first ones content.
Strange is that it appears to be detected correctly on the login screen: It has a different background image there. But when the login progress bar reaches about 70-80%, the first screen gets duplicated.
System Settings -> Hardware -> Display and Monitor -> Display Configuration is showing only the first monitor in the image, but the second one is available in the select field "Primary display".
I'm using an nvidia graphics card, if that is somehow important.
Thanks for any help.

A: I unchecked the "Enabled" checkbox under "System Settings -> Hardware -> Display and Monitor -> Display Configuration" for one monitor and after rechecking it, the monitor reappeared next to the other one. So it's working again now.

A: My solution steps below;

*

*Connect hdmi cable

*Write to terminal xrandr -q

*Press the special button for extend monitor(Fn+F7 or Fn+F10 for lenovo series)

*Choose extend options(For example "Extend to write") and press enter

A: Check what driver is being used.
If it says that there is a custom driver being used, open a terminal of your choice and run:
sudo ubuntu-drivers autoinstall.
Once completed, reboot by either selecting the Reboot option in the GNOME power menu or run reboot in the terminal.