text:
Q: Using Spark on Hive via Eclipse We are using JDBC APIs to connect to HIVE through Eclipse programs to access hive tables, below is the code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import org.testng.annotations.Test;

public class FetchHiveData_test {

private static String driverName = "org.apache.hive.jdbc.HiveDriver";

  @Test
  public void  FetchHiveDataMethod() {
  ResultSet hiveres=null;
  try {
      System.out.println("Inside Hive Method");
      Class.forName(driverName);

      /*********** Hive ***************/
    Connection con = DriverManager.getConnection("jdbc:hive2://XXXXX:20000", "xxxxxx", "yyyyy");
    Statement stmt = con.createStatement();
    String sql="select count(*) from table";
    hiveres = stmt.executeQuery(sql);

    ResultSetMetaData rsmd = hiveres.getMetaData();
    int numCols = rsmd.getColumnCount();
   for(int j=1;j<=numCols;j++){
        System.out.print(rsmd.getColumnName(j)+" ");
    }

    while (hiveres.next()) {

        //Print one row
        for(int i = 1 ; i <= numCols; i++){

              System.out.print(hiveres.getString(i) + " "); //Print one element of a row

        }

          System.out.println();//Move to the next line to print the next row.

            }

  } catch (Exception e) {

  e.printStackTrace();

}

}}

Methods here makes use of spark context however not sure where it takes the server name and credentials, how can I modify the above program to make use of spark? This is to make our queries to run faster as the JDBC APIs are bit slow.
Spark Code:
import java.util.List;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.Function;
import org.apache.spark.sql.api.java.JavaSchemaRDD;
import org.apache.spark.sql.api.java.Row;
import org.apache.spark.sql.hive.api.java.JavaHiveContext;
import org.apache.spark.rdd.*;
import org.testng.annotations.Test;

public class SparkTest {

@SuppressWarnings("serial")
@Test
  public void f() {
    final SparkConf sparkConf = new SparkConf().setMaster("xxxxx:20000").setAppName("HiveConnector");
    final JavaSparkContext sparkContext = new JavaSparkContext(sparkConf);
    JavaHiveContext hiveCtx = new JavaHiveContext(sparkContext);
    JavaSchemaRDD rdd = hiveCtx.sql("Select count(*) from table");
        JavaRDD<Integer> keys = rdd.map(new Function<Row, Integer>() {
            public Integer call(Row row) { return row.getInt(0); }
            });
    List<Integer> res= keys.collect();
    for(Integer val:res){
            System.out.println("val "+val);
   }
    }
}

A: Try running
http://spark.apache.org/docs/latest/sql-programming-guide.html#running-the-thrift-jdbcodbc-server and you will be able to access it through jdbc like in hive.
Note: This might not support all hiveQl.


text:
Q: Colocar um array estado dentro de outro Gostaria de saber como consigo colocar o conteúdo de um array que esteja com status true dentro de outro array, ficando por exemplo:
{ id:1, fruit:'Banana', status:true },
{ id:2, fruit:'Orange', status:true },
{ id:3, fruit:'Lemon', status:true }
Tentei fazer conforme o código abaixo, mas ele está colocando o item como array dentro do outro e não só o conteúdo:

const [fruits,setFruits] = useState([
    {
        id:1,
        fruit:'Banana',
        status:true,
    },
    {
        id:2,
        fruit:'Orange',
        status:true
    }
]);
const [newFruit, setNewFruit] = useState([
    {
        id:3,
        fruit:'lemon',
        status:true
    },
    {
        id:4,
        fruit:'morango',
        status:false
    }
]);

código JSX abaixo:
return (

        {fruits.map((fruits,index)=>
            {fruits.fruit},
        )
        }
        <button onClick={Add}>Adicionar</button>

);

Função para adicionar nova fruta:
const Add = () =>{
    const filtered = newFruit.map((fruit)=>
        fruit.status === true
        ?   {
                fruit
            }

        :   {

            }
    )

    setFruits([
        ...fruits,
        filtered
    ])
    console.log(fruits)
}

A: Basta desestruturar o array filtered como você fez com o array fruits:
setFruits([
    ...fruits,
    ...filtered
]);

Mas também tem o detalhe que esse array filtered não está sendo montado corretamente. Você está gerando ele com o método map, que gera um novo array com o mesmo tamanho do array em que ele foi chamado, e no seu código você está retornando um objeto vazio quando ele não passa pela sua condição fruit.status === true. Isso é desnecessário, você pode apenas utilizar o método filter para gerar um novo array:
const filtered = newFruit.filter((fruit) => fruit.status);

setFruits([
    ...fruits,
    ...filtered
]);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Puppet reporting without master I am planning a Puppet infrastructure for about 100-200 servers. This is the design so far:

*

*Stash (git) for storing puppet config (not planning on using a master).

*Hiera to query either yaml, json, or possibly couchdb for sensitive (passwords) variables.

*PuppetDB?

Point 3 is my problem. I need reporting and it seems like PuppetDB will collect everything I need. However, as I understand, it will only collect and present the data in a REST api. My question is, what then would I (can I) use to grab that data and present it in a clean, view-able way? Do I need PuppetDB for this or can I have my nodes send their reports to a different report processor?
Update 1:
Not sure if this matters, but we are about 70/30 Linux/Windows.

A: Yes, Puppet is rather flexible about reports. There are a number of processors to choose from, and you will most likely end up with a bunch of pson (JSON) files.
This allows you to implement your own consumer for reports, though open source solutions will obviously lift a lot of work from you.


text:
Q: Android AudioRecorder Assertion failed: !(stepCount <= mUnreleased && mUnreleased <= mFrameCount) I am using audio recorder, i am not able to identify where the error is thrown! the app crashes ...
 for (int rate : new int[]{8000, 11025, 16000, 22050, 44100}) {
        mBufferSize = AudioRecord.getMinBufferSize(rate, AudioFormat
                .CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT);
    }

 mAudioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC,
                RECORDER_SAMPLERATE,
                RECORDER_CHANNELS,
                RECORDER_AUDIO_ENCODING,
                mBufferSize);

i refered stack but didn;t find relevant answer...
stack strace :
01-05 18:25:19.863 21646-23485/com.voicy.demo A/AudioTrackShared: Assertion failed: !(stepCount <= mUnreleased && mUnreleased <= mFrameCount)
01-05 18:25:19.863 21646-23485/com.voicy.demo A/libc: Fatal signal 6 (SIGABRT) at 0x0000548e (code=-6), thread 23485 (AudioRecorder T)
01-05 18:25:20.333 1061-1107/? E/InputDispatcher: channel '424b68b0 com.voicy.demo/com.voicy.demo.ui.HomePageActivity (server)' ~ Channel is unrecoverably broken and will be disposed!
01-05 18:25:20.333 1061-1107/? E/InputDispatcher: channel '42d324d0 com.voicy.demo/com.voicy.demo.ui.HomePageActivity (server)' ~ Channel is unrecoverably broken and will be disposed!
01-05 18:25:20.333 1061-1107/? E/InputDispatcher: channel '424b3a60 com.voicy.demo/com.voicy.demo.ui.ChatMessageActivity (server)' ~ Channel is unrecoverably broken and will be disposed!

A: *

*What's with:
for (int rate : new int[]{8000, 11025, 16000, 22050, 44100}) {
    mBufferSize = AudioRecord.getMinBufferSize(rate, AudioFormat
    .CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT);
}

This is calculating mBufferSize with different values, eventually ending with 44100, which admittedly will be a safe number.
In this case, it should be:
mBufferSize = AudioRecord.getMinBufferSize(RECORDER_SAMPLERATE,
                                           RECORDER_CHANNELS,
                                           RECORDER_AUDIO_ENCODING);

*Error is likely caused by the source buffer being disposed in mid-air.
Get inspired by this or that StackOverflow answer.


text:
Q: Drawing cube 3D using Opengl I want to draw a 3D cube using OpenGL this is my code how can correct error
float ver[8][3] =
{
    {-1.0,-1.0,1.0},
    {-1.0,1.0,1.0},
    {1.0,1.0,1.0},
    {1.0,-1.0,1.0},

    {-1.0,1.0,-1.0},
    {1.0,1.0,-1.0},

};

GLfloat color[8][3] =
{
    {0.0,0.0,0.0},
    {1.0,0.0,0.0},
    {1.0,1.0,0.0},
    {0.0,1.0,0.0},

    {1.0,1.0,1.0},
    {0.0,1.0,1.0},
};

void quad(int a,int b,int c,int d)
{
    glBegin(GL_QUADS);
    glColor3fv(color[a]);
    glVertex3fv(ver[a]);

    glColor3fv(color[b]);
    glVertex3fv(ver[b]);

    glColor3fv(color[d]);
    glVertex3fv(ver[d]);
    glEnd();
}

void colorcube()
{
    quad(0,3,2,1);
    quad(2,3,7,6);
}
void display(){
    //  Clear screen and Z-buffer
    glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);

    // Reset transformations
    glLoadIdentity();
    colorcube();
}

int main( int argc, char **argv )
{
    glutInit( &argc, argv );
    glutInitDisplayMode( GLUT_RGBA | GLUT_DEPTH | GLUT_DOUBLE );
    glutInitWindowSize( 640, 480 );
    glutCreateWindow( "GLUT" );
    glutDisplayFunc( display );
    glutDisplayFunc(specialKeys);
    glEnable( GL_DEPTH_TEST );
    glutMainLoop();
    return 0;
}

A: You need to do a few things:

*

*Pass specialKeys into glutSpecialFunc(), not glutDisplayFunc()

*Set the GL_PROJECTION and GL_MODELVIEW matrices

*Move the camera back a bit

*Add a glutSwapBuffers() to the end of display()
Example:
#include <GL/glut.h>

float ver[8][3] =
{
    {-1.0,-1.0,1.0},
    {-1.0,1.0,1.0},
    {1.0,1.0,1.0},
    {1.0,-1.0,1.0},
    {-1.0,-1.0,-1.0},
    {-1.0,1.0,-1.0},
    {1.0,1.0,-1.0},
    {1.0,-1.0,-1.0},
};

GLfloat color[8][3] =
{
    {0.0,0.0,0.0},
    {1.0,0.0,0.0},
    {1.0,1.0,0.0},
    {0.0,1.0,0.0},
    {0.0,0.0,1.0},
    {1.0,0.0,1.0},
    {1.0,1.0,1.0},
    {0.0,1.0,1.0},
};

void quad(int a,int b,int c,int d)
{
    glBegin(GL_QUADS);
    glColor3fv(color[a]);
    glVertex3fv(ver[a]);

    glColor3fv(color[b]);
    glVertex3fv(ver[b]);

    glColor3fv(color[c]);
    glVertex3fv(ver[c]);

    glColor3fv(color[d]);
    glVertex3fv(ver[d]);
    glEnd();
}

void colorcube()
{
    quad(0,3,2,1);
    quad(2,3,7,6);
    quad(0,4,7,3);
    quad(1,2,6,5);
    quad(4,5,6,7);
    quad(0,1,5,4);
}

double rotate_y = 0;
double rotate_x = 0;
void specialKeys( int key, int x, int y )
{
    if (key == GLUT_KEY_RIGHT)
        rotate_y += 5;
    else if (key == GLUT_KEY_LEFT)
        rotate_y -= 5;
    else if (key == GLUT_KEY_UP)
        rotate_x += 5;
    else if (key == GLUT_KEY_DOWN)
        rotate_x -= 5;
    glutPostRedisplay();
}

void display()
{
    glClearColor( 0, 0, 0, 1 );
    glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);

    glMatrixMode( GL_PROJECTION );
    glLoadIdentity();
    int w = glutGet( GLUT_WINDOW_WIDTH );
    int h = glutGet( GLUT_WINDOW_HEIGHT );
    gluPerspective( 60, w / h, 0.1, 100 );

    glMatrixMode( GL_MODELVIEW );
    glLoadIdentity();
    gluLookAt
        (
        3, 3, 3,
        0, 0, 0,
        0, 0, 1
        );

    glRotatef( rotate_x, 1.0, 0.0, 0.0 );
    glRotatef( rotate_y, 0.0, 1.0, 0.0 );
    colorcube();

    glutSwapBuffers();
}

int main( int argc, char **argv )
{
    glutInit( &argc, argv );
    glutInitDisplayMode( GLUT_RGBA | GLUT_DEPTH | GLUT_DOUBLE );
    glutInitWindowSize( 640, 480 );
    glutCreateWindow( "GLUT" );
    glutDisplayFunc( display );
    glutSpecialFunc( specialKeys );
    glEnable( GL_DEPTH_TEST );
    glutMainLoop();
    return 0;
}


text:
Q: Printing a Modal with a Gridview + Formatting Hello so I'm trying to Print out a modal with all of the data in the modal but I'm running into a problem with formatting. The Gridview get's cut off and the text are not the way it should be. Any advice on how to make it look better?

                            <button type="button" class="close" data-dismiss="modal">×</button>

Trip Summary

                                        Date:

                                            <asp:Label runat="server" ID="lblDate"></asp:Label>

                                        Volunteer Assigned:

                                            <asp:Label runat="server" ID="lblVolunteer"></asp:Label>

                                        Starting Address:

                                            <asp:Label runat="server" ID="lblStartingAddress"></asp:Label>

                                        Number Of Boxes:

                                            <asp:Label runat="server" ID="lblNumBoxes"></asp:Label>

                                        Trip has food?

                                            <asp:Label runat="server" ID="lblHasFood"></asp:Label>

                                        Total Trip Time:

                                            <asp:Label runat="server" ID="lblTotalTripTime"> 2 hours and 30 minutes </asp:Label>

                                        List of Destinations:

                                        Print Summary

                                        <%--<asp:LinkButton
                                            Style="width: 3.5em;" OnClick="btnPrint1_Click" runat="server" title="Print Trip Summary" data-toggle="tooltip" class="glyphicon glyphicon-print">Print Summary
                                        </asp:LinkButton>--%>

                                        <asp:GridView ID="GVSummary" runat="server" Style="overflow-x: scroll; overflow-y: scroll" CssClass="table table-responsive table-bordered" AutoGenerateColumns="false">
                                            <Columns>
                                                <asp:BoundField DataField="DestName" HeaderText="Name" />
                                                <asp:BoundField DataField="isPickup" HeaderText="Pick Up or Delivery" />
                                                <asp:BoundField DataField="Address1" HeaderText="Address 1" />
                                                <asp:BoundField DataField="Address2" HeaderText="Address 2" />
                                                <asp:BoundField DataField="City" HeaderText="City" />
                                                <asp:BoundField DataField="State" HeaderText="State" />
                                                <asp:BoundField DataField="ZipCode" HeaderText="Zip Code" />
                                                <asp:BoundField DataField="RegionName" HeaderText="Region" />
                                                <asp:BoundField DataField="DestinationPriority" HeaderText="Priority" />
                                                <asp:BoundField DataField="DesTime" HeaderText="Travel Time" />
                                                <asp:BoundField DataField="isScheduled" HeaderText="Recurring" />
                                                <asp:BoundField DataField="DesNotes" HeaderText="Notes" />
                                                <%-- <asp:BoundField DataField="DesNotes" HeaderText="Notes" />
                                                <asp:BoundField DataField="isFood" HeaderText="Notes" />
                                                <asp:BoundField DataField="BoxesNumber" HeaderText="Notes" />
                                                <asp:BoundField DataField="DesTime" HeaderText="Notes" />
                                                <asp:BoundField DataField="DesNotes" HeaderText="Notes" />
                                                <asp:BoundField DataField="DesNotes" HeaderText="Notes" />--%>
                                            </Columns>
                                        </asp:GridView>

A: You can use CSS on the printwindow page with the following line:
printWindow.document.write('<link href="/css/style.css" rel="stylesheet" />');
Use whatever CSS you used for the page.


text:
Q: Regex to match begin pattern and first AND ONLY FIRST occurrence of end pattern I have the following text:
Global
    GlobalSection(TeamFoundationVersionControl) = preSolution
        Blah Blah
        Blah Blah
    EndGlobalSection
    GlobalSection(SolutionConfigurationPlatforms) = preSolution
        Blah Blah
        Blah Blah
    EndGlobalSection
EndGlobal

and the following regex:
GlobalSection\(TeamFoundationVersionControl\)((.|\n)*)(EndGlobalSection\r)

I want to find just the first GlobalSection for TeamFoundationVersionControl i.e. just the following:
GlobalSection(TeamFoundationVersionControl) = preSolution
        Blah Blah
        Blah Blah
    EndGlobalSection
The regex isn't working!  It selects the following i.e. BOTH sections (wrong!):
       GlobalSection(TeamFoundationVersionControl) = preSolution
            Blah Blah
            Blah Blah
        EndGlobalSection
        GlobalSection(SolutionConfigurationPlatforms) = preSolution
            Blah Blah
            Blah Blah
        EndGlobalSection

I need it to stop at the FIRST occurrence of EndGlobalSection.  Please help!
BTW: I am testing this with Regex Storm , an online RegEx tester.
Thank You!

A: You can use the non-greedy *? operator, it'll terminate as soon as possible (before the first EndGlobalSection):
GlobalSection\(TeamFoundationVersionControl\)((.|\n)*?)EndGlobalSection

Demo here.
If the regex engine you use supports inline modifiers, you can activate the DOTALL (or single-line) mode, allowing the dot to match newline characters (use the s modifier, except in Ruby where it's called m):
(?s)GlobalSection\(TeamFoundationVersionControl\)(.*?)EndGlobalSection


text:
Q: PXE boot via off-site TFTP server I would like to PXE boot from a TFTP server that is not on my local network. The server is running in a cloud VM.
Is it possible to specify the remote server's IP without utilizing DHCP?
If not, what would the simplest pass-through method be to proxy requests via another working PC on the local subnet?

A: DHCP is an element of PXE. There is no PXE without DHCP.
There are older methods of network booting, such as DHCP's direct ancestors BOOTP and RARP, but then, those are also unrelated to PXE other than the shared ancestry.
I'd say the simplest way to do what you want is to run a DHCP server on the "other working PC on the local subnet". You likely already have a DHCP server, but if it's just the one within your Internet modem/router/gateway, it's probably not very featureful. You'll thus get other benefits by replacing it.
The two standard options are ISC DHCP and dnsmasq. Most of the instructions you'll find on PXE assume ISC DHCP, and it's fairly easy to set up, but dnsmasq is easier in some ways and also gets you a DNS server suitable for managing a small LAN.

A: I suggest you take a look at ipxe.
It is possible to configure ipxe to take a specific IP address and then boot from the internet.
Their examples section is pretty extensive, I'm cannot guarantee you'll find exactly what you need, but you can probably work from there. There's documentation on how to build your own pxeboot.0 kernel, and even a boot ROM for your NIC.


text:
Q: Error: Uncaught (in promise): TypeError: Object(...) is not a function TypeError: Object(...) is not a function I am trying to add speech recognition in my ionic app but I get the following error when I add speech recognition
Versions used:-
ionic-framework - 3.9.2
ionic-app - 3.1.2
angular-core - 5.0.0
I have added the speech recognition only in a new ionic3 initialised app.
import { BrowserModule } from '@angular/platform-browser';
import { ErrorHandler, NgModule } from '@angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { SplashScreen } from '@ionic-native/splash-screen';
import { StatusBar } from '@ionic-native/status-bar';
import {SpeechRecognition} from '@ionic-native/speech-recognition/ngx';

import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';

@NgModule({
  declarations: [
    MyApp,
    HomePage
  ],
  imports: [
    BrowserModule,
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage
  ],
  providers: [
    StatusBar,
    SplashScreen,
    SpeechRecognition,
    {provide: ErrorHandler, useClass: IonicErrorHandler}
  ]
})
export class AppModule {}

app.module.ts
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import {SpeechRecognition} from '@ionic-native/speech-recognition/ngx';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  bgcolor: string = "white";

  constructor(public navCtrl: NavController,private speechRecognition: SpeechRecognition ) {

  }

  ngOnInit(){

    this.speechRecognition.hasPermission()
    .then((hasPermission: boolean)=>{
      if(!hasPermission){
        this.speechRecognition.requestPermission().then(
          () => console.log('Granted'),
          () => console.log('Denied')
        )
      }
    })
  }

  start(){
    this.speechRecognition.startListening().subscribe(
      (matches: Array<string>)=>{
        this.bgcolor = matches[0]
      }
    )
  }

}

home.ts
{
  "name": "old",
  "version": "0.0.1",
  "author": "Ionic Framework",
  "homepage": "http://ionicframework.com/",
  "private": true,
  "scripts": {
    "clean": "ionic-app-scripts clean",
    "build": "ionic-app-scripts build",
    "lint": "ionic-app-scripts lint",
    "ionic:build": "ionic-app-scripts build",
    "ionic:serve": "ionic-app-scripts serve"
  },
  "dependencies": {
    "@angular/common": "5.0.0",
    "@angular/compiler": "5.0.0",
    "@angular/compiler-cli": "5.0.0",
    "@angular/core": "5.0.0",
    "@angular/forms": "5.0.0",
    "@angular/http": "5.0.0",
    "@angular/platform-browser": "5.0.0",
    "@angular/platform-browser-dynamic": "5.0.0",
    "@ionic-native/core": "4.3.2",
    "@ionic-native/speech-recognition": "^4.20.0",
    "@ionic-native/splash-screen": "4.3.2",
    "@ionic-native/status-bar": "4.3.2",
    "@ionic/storage": "2.1.3",
    "cordova-android": "8.0.0",
    "cordova-plugin-speechrecognition": "1.2.0",
    "ionic-angular": "3.9.2",
    "ionicons": "3.0.0",
    "rxjs": "^6.0.0",
    "rxjs-compat": "^6.5.2",
    "sw-toolbox": "3.6.0",
    "zone.js": "0.8.18"
  },
  "devDependencies": {
    "@ionic/app-scripts": "3.1.0",
    "@ionic/cli-plugin-cordova": "1.6.2",
    "@ionic/cli-plugin-ionic-angular": "1.4.1",
    "cordova-plugin-device": "^1.1.4",
    "cordova-plugin-ionic-webview": "^1.2.1",
    "cordova-plugin-splashscreen": "^4.0.3",
    "cordova-plugin-whitelist": "^1.3.1",
    "ionic-plugin-keyboard": "^2.2.1",
    "typescript": "2.4.2"
  },
  "description": "An Ionic project",
  "cordova": {
    "plugins": {
      "cordova-plugin-speechrecognition": {},
      "ionic-plugin-keyboard": {},
      "cordova-plugin-whitelist": {},
      "cordova-plugin-device": {},
      "cordova-plugin-splashscreen": {},
      "cordova-plugin-ionic-webview": {}
    },
    "platforms": [
      "android"
    ]
  }
}

package.json
I have been unable to find answers that helped me so far. I believe this can be a version compatibitlity issue.


text:
Q: Receiving 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference I am new to android development and scripting with java. I am trying to create an app that allows me to toggle the internal microphone on and off via a switch. I found two scirpts (a switch script and a microphone control script) and I have peaced them together, correcting any debugging issues as I go and currently the script shows up clean. However when it is run on a phone or simulator it crashes immediately posting the following error,

android.content.Context android.content.Context.getApplicationContext()' on a null object reference"focused around my use of import android.content.Context;.

The error appears to be based on the Context.getApplicationContext request failing to find a result and thus posting NULL.
I have looked at a long list of other people suffering from similar areas, but all solutions seem to focus on changes to different areas of their code which I cannot relate back to my own scripts.
package com.example.myfirstapp;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.media.AudioManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Switch;

public class MainActivity extends AppCompatActivity {

    private Switch sw1;
    Button btnGet;
    Context context = getApplicationContext();
    AudioManager audioManager = ((AudioManager)context.getSystemService(Context.AUDIO_SERVICE));
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        audioManager.setStreamMute(AudioManager.STREAM_SYSTEM, true);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        sw1 = findViewById(R.id.switch1);
        btnGet = findViewById(R.id.getBtn);
        btnGet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (sw1.isChecked()) {
                    audioManager.setMicrophoneMute(false);
                }
                else {
                    audioManager.setMicrophoneMute(true);
                }

            }
        });
    }
}

The expected result, even if the script doesn't work, is that I am able to run the app, currently the app crashes on startup and posts the following error message...
[Logcat]
2019-08-20 13:23:01.710 5559-5559/com.example.myfirstapp E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.myfirstapp, PID: 5559
    java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.myfirstapp/com.example.myfirstapp.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2548)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
        at android.app.ActivityThread.-wrap12(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6077)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
        at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:106)
        at com.example.myfirstapp.MainActivity.<init>(MainActivity.java:16)
        at java.lang.Class.newInstance(Native Method)
        at android.app.Instrumentation.newActivity(Instrumentation.java:1078)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2538)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
        at android.app.ActivityThread.-wrap12(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6077)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)

A: Your issue is that you are attempting to retrieve the context at initialization ie.
Context context = getApplicationContext();

There is no guarantee that getApplicationContext(); will return a valid value until the activity has been created. In this case it is null and when you attempt to access it on the next line you get a null pointer exception. You need to instead assign the variable context within the onCreate() along with the audio manager.
For example, like so:
    Context context;
    AudioManager audioManager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = getApplicationContext();
        audioManager = ((AudioManager)context.getSystemService(Context.AUDIO_SERVICE));
    ...
    }

Another thing to note is that the Activity class is a subclass of Context, so you do not need to retrieve the application context you can instead write
    AudioManager audioManager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        audioManager = ((AudioManager)getSystemService(Context.AUDIO_SERVICE));
    ...
    }

A: I guess, the problem here is this line:
Context context = getApplicationContext();

Instead of initializing it as a class field, initialize it inside onCreate() method.
For Example:
public class MainActivity extends AppCompatActivity {

private Switch sw1;
Button btnGet;
Context context;
AudioManager audioManager;
@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    audioManager = ((AudioManager)getSystemService(Context.AUDIO_SERVICE));
    audioManager.setStreamMute(AudioManager.STREAM_SYSTEM, true);
    context = getApplicationContext();

    setContentView(R.layout.activity_main);
    sw1 = findViewById(R.id.switch1);
    btnGet = findViewById(R.id.getBtn);
    .
    .


text:
Q: Lamdify a function keeping some symbols I'm trying to lamdify a SymPy expression to a NumPy evaluated function, but keeping some symbols of the original expression. It works for some simple expressions
>>> x,y,z=sympy.symbols('x y z')
>>> expr1=(x+y)*z
>>> func1=sympy.lambdify((x,y),expr1,modules='numpy')
>>> func1(1.,1.)
2.0*z

but when I try some other more complicated like:
>>> expr2=sympy.exp((x+y)*z)
>>> func2=sympy.lambdify((x,y),expr2,modules='numpy')
>>> func2(1.,1.)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <lambda>
AttributeError: 'Mul' object has no attribute 'exp'

I get this error. Any suggestion would be welcome!

A: Have you checked whether using "sympy" in modules would do the job? It seems to work on your little example. We just need to know whether it will give you what you expect from the "numpy" option.
I had this issue before working with complex numbers in polar form. Using "sympy" just solve the problem and, until now, I've been able to work with them without troubles.
import sympy as sp

x, y, z = sp.symbols("x y z")
expr2 = sp.exp((x + y) * z)
func2 = sp.lambdify((x, y), expr2, modules="sympy")
func2(1., 1)


text:
Q: Jenkins: send email from python How to send email utilizing python code from Jenkins job? I have SMTP configuration with Groovy-DSL "emailext", I can accomplish it; But trying to see the same with python code.

A: Simple example:
import smtplib
sender = "sender@domain.com"
receivers = "receivers@domain.com"
message = """
Stack Overflow!
"""

try:
   smtp_obj = smtplib.SMTP('localhost')
   smtp_obj.sendmail(sender, receivers, message)
   print "Done"
except SMTPException:
   print "error"

You can read this
https://www.tutorialspoint.com/python/python_sending_email.htm


text:
Q: How to put a default value into an 'input' and when user press enter it will disappear? How to put default value to input and when user press enter it will disappear?
My code that is not working:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<body>
    <input  value="default-value" type="text"/>
</body>
</html>

A: When HTML5 will be supported by many browsers, it is very easy:
<input type="text" placeholder="default-value" />

Until than I would use a background image and let it disappear it a user focuses the input, as otherwise a user might submit the default value and you have to filter it out server side:
<input type="text" name="fieldname" id="fieldname" style="background-image: url("default-value.png"); background-repeat: no-repeat;" />

And the JavaScript to remove it on click (uses prototype framework):
$('fieldname').observe('click', function() {
 // if already cleared, do nothing
 if(this._cleared) return;
 this.setStyle({backgroundImage: ''});
 this._cleared = true
});

A: Here is an example of a search box with the initial value 'enter search string here'. A bit of javascript clears out the box when the control gets the focus and begins typing:
<input name="txtSearch" id="txtSearch" onfocus="if (this.value=='enter search string here...') this.value = ''" value="enter search string here..." type="text">

A: Don't put a default value. Just remove the value attribute.
It is not clear from your question what your goal is - however, by using a default value as you have, every time the page is loaded this value will be present.
Your page doesn't have a form element either, which is required for form submission.


text:
Q: How To Reset a Binding from Code Behind on a Window I have a Tab Control containing a Control in each tab item and a Slider in the Status bar that has to be Bound on the fly to a Field in the Currently active TabItem control. I Will bind it using the code behind, but seeing that the user can switch multiple times from a tab to another and that the control has a SetBinding method but not a ResetBinding method I was wondering if There was Something to clear the Binding before setting the new control value something like:
myslider.RemovePreviousBinding
...
mySlider.SetBinding(Slider.Value, mynewBinding);

Or it does not bother and the previous binding is reset when I set the new one. I don't like the Idea of having memory leaks or multiple bindings making strange behaviors to the controls.
Thank you in advance

A: You should use BindingOperations.ClearBinding
https://msdn.microsoft.com/it-it/library/system.windows.data.bindingoperations.clearbinding%28v=vs.110%29.aspx


text:
Q: Java: how to detect the real, unfakeable user language and user country? For our Java application, we are considering to toughen our licensing conditions and related code for certain countries for which we are experiencing massive license infringement. Therefore we want to find out the real user language and user country. I'm aware, that you can query system properties user.language and user.country, but these can easily be faked when starting the Java application using e.g. -Duser.language=en. Is there a way to detect the original, unaltered values for these properties? Or is there another API which gives us the real settings?
Note:

*

*the solution should require only a small computational effort and no Internet connection

*we are not looking for a perfectly safe solution, but it also shouldn't be too easy to fake (like with system properties).

A: Do not even try. You are trying to solve at a technical level a legal question. I once used a Linux machine where different users had different declared languages and time zones, and still have a VM using "C" language et UTC time zone.
As per my experience, such controls can annoy well intentioned users that happen to use a non standard configuration, but cannot prevent someone to deliberately give a wrong information.
So my advice is:

*

*use the system property to get the declared country

*ask the user to confirm or change it

*trust what user declared

It could save you number of hotline calls.


text:
Q: Android: Get the X and Y coordinates of a TextView? I am working now on a project. I have 2 draggable textView in a circle. I want to add those value inside the circle when the circle is drag over the other circle. the first option that I have is to get the X and Y of the circle, but I get it. Can anyone fix my code?
Here is the Code:
MainActivity
public class MainActivity extends Activity {
int windowwidth;
int windowheight;
TextView bola;
TextView bola2;
private float x;
private float y;

private android.widget.RelativeLayout.LayoutParams layoutParams;

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

    windowwidth = getWindowManager().getDefaultDisplay().getWidth();
    windowheight = getWindowManager().getDefaultDisplay().getHeight();

    bola = (TextView) findViewById(R.id.ball);
    bola2 = (TextView) findViewById(R.id.ball2);

    bola2.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            // TODO Auto-generated method stub
            layoutParams = (RelativeLayout.LayoutParams) bola2
                    .getLayoutParams();
            switch (event.getActionMasked()) {
            case MotionEvent.ACTION_DOWN:
                break;

            case MotionEvent.ACTION_MOVE:
                int x_cord = (int) event.getRawX();
                int y_cord = (int) event.getRawY();

                if (x_cord > windowwidth) {
                    x_cord = windowwidth;
                }
                if (y_cord > windowheight) {
                    y_cord = windowheight;
                }
                layoutParams.leftMargin = x_cord - 25;
                layoutParams.topMargin = y_cord - 75;
                bola2.setLayoutParams(layoutParams);
                break;

            default:
                break;
            }
            return true;
        }
    });

    bola.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            layoutParams = (RelativeLayout.LayoutParams) bola
                    .getLayoutParams();
            switch (event.getActionMasked()) {
            case MotionEvent.ACTION_DOWN:

                break;

            case MotionEvent.ACTION_MOVE:
                int x_cord = (int) event.getRawX();
                int y_cord = (int) event.getRawY();

                if (x_cord > windowwidth) {
                    x_cord = windowwidth;
                }
                if (y_cord > windowheight) {
                    y_cord = windowheight;
                }
                layoutParams.leftMargin = x_cord - 25;
                layoutParams.topMargin = y_cord - 75;
                bola.setLayoutParams(layoutParams);
                break;

            default:
                break;
            }
            // TODO Auto-generated method stub
            return true;
        }
    });

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}}

Activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<TextView
    android:id= "@+id/ball"
    android:background="@drawable/bgshape"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="1"
    tools:context=".MainActivity" />
 <TextView
    android:id= "@+id/ball2"
    android:background="@drawable/bgshape"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="2"
    tools:context=".MainActivity"
    android:layout_x="60dp"
    android:layout_y="20dp"
    />

The bgshape.xml(for the circle)
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >

<padding
    android:bottom="20dp"
    android:left="25dp"
    android:right="25dp"
    android:top="20dp" />

<stroke
    android:width="2dp"
    android:color="#000000" />

<solid android:color="#ffffff" />

<corners
    android:bottomLeftRadius="30dp"
    android:bottomRightRadius="30dp"
    android:topLeftRadius="30dp"
    android:topRightRadius="30dp" />

This code works well. Could anyone fix this so that I can add the value inside the circle when they hit each other?

A: Try this :
getLeft() and getTop() will return you the starting x,y co-ordinates.


text:
Q: Font awesome icon is moving outside of its parent container with position:absolute I have a font awesome icon in a wrapper div.  The wrapper div has a positioning of absolute.  The font awesome icon also has a position of absolute.  The wrapper div needs to have absolute positioning because I am going to put it on the bottom edge of my header tag (not included in the code provided).
When I take away "position: absolute" from the font awesome icon, the icon no longer fits in the parent container.  I'm confused on why this is happening.  The parent to the icon is '.wrapper'  Therefore, by absolutely positioning the font awesome icon, I should be able to move it exactly where I want it to go inside '.wrapper', but instead it is moving outside of the wrapper class's border.
Here is when the icon has position: absolute:

Learn more

CSS:
header .wrapper {
    border: 2px solid red;
    font-size: 400%;
    position: absolute;
    bottom: 0;
    left: 50%;
}

header .wrapper i {
    position: absolute;
}

header .wrapper p {
    align-content: center;
    font-size: 30%;
}

[codepen] https://codepen.io/anon/pen/yZXMzg?editors=1100
Here is when the icon does not have position: absolute:

header .wrapper {
    border: 2px solid red;
    font-size: 400%;
    position: absolute;
    bottom: 0;
    left: 50%;
}

header .wrapper i {
}

header .wrapper p {
    align-content: center;
    font-size: 30%;
}

[codepen] https://codepen.io/anon/pen/zezwKM

A: This is expected behavior.

The element is removed from the normal document flow, and no space is created for the element in the page layout. It is positioned relative to its closest positioned ancestor, if any; otherwise, it is placed relative to the initial containing block. Its final position is determined by the values of top, right, bottom, and left.
  https://developer.mozilla.org/en-US/docs/Web/CSS/position

That is to say, when your icon is position: absolute, the parent container sizes itself as if the icon was not there (strictly, the icon takes up no space). So while you can indeed position it using position: absolute you'll just need to manually add spacing (e.g. using padding on the parent) to add enough space for it.
example: https://codepen.io/anon/pen/jdwmZz?editors=1100
Depending on your needs here it may be easier to just position: static to FontAwesome element (I also put the i element inside the p to avoid line break issues). https://codepen.io/anon/pen/Odgmvm?editors=1100


text:
Q: find match between sheets by loop of multiple range in vba hello just started in vba for excel
With two sheets, what is the best way to take
sheet(1).range(a:a)
and find matching values in
sheet(2).range(a:a)
then sum the "total" values in sheets(2).range(b:b) for each match found back
into sheet(1).range(b:b) ?
if there is no matching value highlight red on sheet 1
highlist green when matching on sheet 2
sheet1:

value
total

24
(1)

3-3
(20)

ss99.
(7)

5
(highlight red)

sheet2:

value
total

3-3
10 (highlight green)

3-3
5  (highlight green)

24
1   (highlight green)

3-3
5   (highlight green)

ss99
7 (highlight green)

empty
empty

This is as much code as I written trying to test the iteration between the two sheets.
but I was getting error once it got to the nested loop
sub match()

 Dim ws1 as worksheet
 Set ws1 as worksheets(1)
 Dim rg1 as range
 Set rg1 = ws1.range("a:a")
 Dim rg1total as range
 Set rg1total = ws1.range("b:b")

 Dim ws2 as worksheet
 Set ws2 as worksheets(1)
 Dim rg2 as range
 Set rg2 = ws2.range("a:a")
 Dim rg2total as range
 Set rg2total = ws2.range("b:b")

 Dim ws1rowcount as long
 Dim ws2rowcount as long

 ws1rowcount = ws1.cells(rows.count, 1).End(xlUp).Row
 ws2rowcount = ws2.cells(rows.count, 1).End(xlUp).Row

 Dim searchvalue as string

 Dim rng1 as range
 Dim rng2 as range

 for each rng in rg1
    for each rng2 in rg2
      MsgBox(rng)
      MsgBox(rng2)
     exit for ''' wont iterate to next in rg2
    next ''' wont iterate outer loop rg1
 next

End Sub

I found on the microsoft docs an example using match function
so I was trying implement this code for my use case..
For each value in the first column of the first worksheet, this example searches through the entire workbook for a matching value. If the macro finds a matching value, it sets the original value on the first worksheet to be bold.
Sub HighlightMatches()
    Application.ScreenUpdating = False

    'Declare variables
    Dim var As Variant, iSheet As Integer, iRow As Long, iRowL As Long, bln As Boolean

       'Set up the count as the number of filled rows in the first column of Sheet1.
       iRowL = Cells(Rows.Count, 1).End(xlUp).Row

       'Cycle through all the cells in that column:
       For iRow = 1 To iRowL
          'For every cell that is not empty, search through the first column in each worksheet in the
          'workbook for a value that matches that cell value.

          If Not IsEmpty(Cells(iRow, 1)) Then
             For iSheet = ActiveSheet.Index + 1 To Worksheets.Count
                bln = False
                var = Application.Match(Cells(iRow, 1).Value, Worksheets(iSheet).Columns(1), 0)

                'If you find a matching value, indicate success by setting bln to true and exit the loop;
                'otherwise, continue searching until you reach the end of the workbook.
                If Not IsError(var) Then
                   bln = True
                   Exit For
                End If
             Next iSheet
          End If

          'If you don't find a matching value, don't bold the value in the original list;
          'if you do find a value, bold it.
          If bln = False Then
             Cells(iRow, 1).Font.Bold = False
             Else
             Cells(iRow, 1).Font.Bold = True
          End If
       Next iRow
    Application.ScreenUpdating = True
End Sub

A: Sum Up Column Data (Dictionary)
Option Explicit

Sub SumUpColumnData()

    ' Define constants.

    ' Source (lookup and read)
    Const sName As String = "Sheet2"
    Const slCol As String = "A" ' 2. ... here...
    Const svCol As String = "B" ' 3. ... and return the sum of these...
    Const sfRow As Long = 2
    ' Destination (lookup and write)
    Const dName As String = "Sheet1"
    Const dlCol As String = "A" ' 1. Lookup this...
    Const dvCol As String = "B" ' 4. ...here.
    Const dfRow As Long = 2

    ' Reference the workbook ('wb').
    Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code

    ' Reference the source worksheet ('sws').
    Dim sws As Worksheet: Set sws = wb.Worksheets(sName)

    ' Reference the source lookup and values
    ' column ranges ('slrg', 'svrg').

    Dim slRow As Long: slRow = sws.Cells(sws.Rows.Count, slCol).End(xlUp).Row

    Dim srCount As Long: srCount = slRow - sfRow + 1

    If srCount < 1 Then
        MsgBox "No data in source column range.", vbExclamation
        Exit Sub
    End If

    Dim slrg As Range: Set slrg = sws.Cells(sfRow, slCol).Resize(srCount)
    Dim svrg As Range: Set svrg = slrg.EntireRow.Columns(svCol)

    ' Write the values from the source lookup and values column ranges
    ' to 2D one-based (one-column) arrays ('slData','svData').

    Dim slData() As Variant
    Dim svData() As Variant

    If srCount = 1 Then ' one cell
        ReDim slData(1 To 1, 1 To 1): slData(1, 1) = slrg.Value
        ReDim svData(1 To 1, 1 To 1): svData(1, 1) = svrg.Value
    Else ' multiple cells
        slData = slrg.Value
        svData = svrg.Value
    End If

    ' Write each unique source lookup value and its corresponding sum
    ' to the 'keys' and 'items' respectively of the source dictionary ('sDict').

    Dim sDict As Object: Set sDict = CreateObject("Scripting.Dictionary")
    sDict.CompareMode = vbTextCompare ' case-insensitive

    Dim slString As String
    Dim svValue As Variant
    Dim sr As Long

    For sr = 1 To srCount
        slString = CStr(slData(sr, 1))
        If Len(slString) > 0 Then ' is not blank
            If Not sDict.Exists(slString) Then ' doesn't exist
                sDict(slString) = 0
            'Else ' exists; do nothing
            End If
            svValue = svData(sr, 1)
            If VarType(svValue) = vbDouble Then ' is a number
                sDict(slString) = sDict(slString) + svValue
            'Else ' is not a number; do nothing
            End If
        'Else ' is blank; do nothing
        End If
    Next sr

    ' Release memory; the source data is in the source dictionary.
    Erase svData
    Erase slData

    ' Validate the source dictionary.
    If sDict.Count = 0 Then
        MsgBox "No valid data found.", vbCritical
        Exit Sub
    End If

    ' Reference the destination worksheet ('sws').
    Dim dws As Worksheet: Set dws = wb.Worksheets(dName)

    ' Reference the destination lookup and values
    ' column ranges ('dlrg', 'dvrg').

    Dim dlRow As Long: dlRow = dws.Cells(dws.Rows.Count, dlCol).End(xlUp).Row

    Dim drCount As Long: drCount = dlRow - dfRow + 1

    If drCount < 1 Then
        MsgBox "No data in destination column range.", vbExclamation
        Exit Sub
    End If

    Dim dlrg As Range: Set dlrg = dws.Cells(dfRow, dlCol).Resize(drCount)
    Dim dvrg As Range: Set dvrg = dlrg.EntireRow.Columns(dvCol)

    ' Write the values from the destination lookup column range
    ' to a 2D one-based (one-column) array ('dlData').

    Dim dlData() As Variant

    If drCount = 1 Then ' one cell
        ReDim dlData(1 To 1, 1 To 1): dlData(1, 1) = dlrg.Value
    Else ' multiple cells
        dlData = dlrg.Value
    End If

    ' Define the destination values array ('dvData'),
    ' a 2D one-based (one-column) array.
    Dim dvData() As Variant: ReDim dvData(1 To drCount, 1 To 1)

    ' Using the destination lookup array and the source dictionary,
    ' write the sums to the destination values array.

    Dim dlString As String
    Dim dr As Long

    For dr = 1 To drCount
        dlString = CStr(dlData(dr, 1))
        If Len(dlString) > 0 Then ' is not blank
            If sDict.Exists(dlString) Then ' found in the source dictionary
                dvData(dr, 1) = sDict(dlString)
            'Else ' not found in the source dictionary; do nothing
            End If
        'Else ' is blank; do nothing
        End If
    Next dr

    ' Release memory; the destination data is in the destination values array.
    Erase dlData
    Set sDict = Nothing

    ' Write the values from the destination values array
    ' to the destination values range.
    dvrg.Value = dvData

    ' Inform to not wonder if the code has run or not.
    MsgBox "Added the sums.", vbInformation

End Sub


text:
Q: NSJSONSerialization leaks in Callback Block I'm trying to use Blocks as callbacks for an API request via the method below. This method takes a Block that is nested in this method's Block.  It works... BUT,
If an Object that has called this method is dealloced, NSJSONSerialization dumps out a massive memory leak.  It's all good while everything is running.  The leak only happens after the requesting object is gone. The leaks are nearly all NSPlaceHolder types.
I'm at my wits end and any ideas are greatly appreciated!
    - (void)sendRequestUsingNSURLConnectionWith:(NSURLRequest *)request andCallback:(void (^)(id))handler
        {
            __block __typeof__(self)blockSelf = self;

            // CL: build a block to be run asynchronously
            ApiClientCallback handleResponse = [[^(NSURLResponse *response, NSData *data, NSError *error) {

                id results = nil;

                // CL: http errors would be caught here.
                if (error) {
                    NSLog(@"[%@ %@] HTTP error: %@", NSStringFromClass([blockSelf class]), NSStringFromSelector(_cmd), error.localizedDescription);
                    results = error;
                }
                else {
                // CL: parse the JSON
                    NSError *jsonError = nil;
                    NSError *apiError = nil;
                    if (data) {
                        results = [NSJSONSerialization JSONObjectWithData:data
                                                                  options:NSJSONReadingMutableContainers
                                                                    error:&jsonError];
                    }
                    else {
                        results = nil;
                    }
                    // CL: json errors would be caught here.
                    if (jsonError) {
                        NSLog(@"[%@ %@] JSON error: %@", NSStringFromClass([blockSelf class]), NSStringFromSelector(_cmd), error.localizedDescription);
                        results = error;
                    }
                    // CL: Check for API errors.
                    else if ([blockSelf checkApiErrorCode:results error:&apiError]) {
                        //CL: if there's an error make the NSError object the result.
                        if (apiError) results = apiError;
                    }
                }
                // CL: Send result to the completion block of the requesting object
                handler(results);

            } copy] autorelease];

            [NSURLConnection sendAsynchronousRequest:request
                                               queue:self.opQueue
                                   completionHandler:handleResponse];
        }

A: Per request I'm documenting the conclusion here. It turned out that I had forgotten to call super dealloc in the dealloc method of a sub class. This caused the super to leak all of it's retained properties upon deallocation. Programmer error. Note that this scenario was happening pre ARC.


text:
Q: How to use different database depending on file location I'm not sure how exactly should I do this. But general idea is that when someone access our script on:
- http://livescript.phpiscool.com OR any of the sub folders
The database should be normal "live" database.
But when someone is trying to enter/navigate:
- http://livescript.phpiscool.com/beta1
OR
- http://livescript.phpiscool.com/beta2
The script should use different database ("beta" database)...
We have databse configuration in config.php and it looks like that:
<?php
$db_host = "localhost";
$db_username = "tureh_user";
$db_password = "crazypssrd";
$db_name = "database_test";
?>

A: $_SERVER['REQUEST_URI'] will contain everything from the first slash after the domain onwards, so checking for it starting at position 0 with '/beta' should do the job
if(strpos(strtolower($_SERVER['REQUEST_URI']),'/beta') === 0)
{
  $db_host = "beta";
}
else
{
  $db_host = "localhost";
}

the explicit comparison (===) means a int of 0 rather than (==) which may give a false positive on "false" if it fails to find a match

A: Most of the time, that kind of problem is handled by a configuration array:
$db['live'] = array(); // Your live configuration
$db['beta'] = array(); // Your beta configuration

$mode = process_url_to_get_mode();

Then, make use of $db[$mode] to instantiate your connection.
That's actually how CodeIgniter does it.
Of course, you can rely on a function like Scuzzy gave you to get $mode.

A: A cleaner solution would be to maintain two copies of your code base, one for the beta and one for the live version. This is trivial if you are using source control such as subversion, which uses a concept similar to folders called "branches" (wikipedia article on Subversion: http://en.wikipedia.org/wiki/Subversion ). The benefits of having two copies of you code for beta and live are;

*

*If you make a change to the BETA edition of the site during development which accidentally breaks the site, the live site won't be affected.

*As your site grows, you can move the BETA or development copy onto a different machine, or your local machine for development at some point.

*You don't litter your code with nasty checks, to see if you are running development/live edition.

If you are using the Apache webserver, you can host these two separate sites to run at the same time using Apache VHosts (assuming you control the server yourself); http://httpd.apache.org/docs/2.0/vhosts/examples.html
In the long term, it is the better solution.


text:
Q: Cohort Data transformation I have the following data:
    signup_date purchase_date nbr_purchase
    2010-12-12             7            2
    2011-01-03             4            1
    2010-11-28             6            2
    2011-01-05            19            9
    2010-11-10            26            3
    2010-11-25            11            2

Where each row corresponds to a customer, signup_date is sign up date, purchase_date is number of days elapsed from sign up and first purchase, nbr_purchase is number of items purchased. I would like to carry cohort analysis and transform the data to look like:
cohort  signed_up  active_m0  active_m1  active_m2
2011-10 12345      10432      8765       6754
2011-11 12345      10432      8765       6754
2011-12 12345      10432      8765       6754

Cohort here is in "YYYY-MM" format, signed_up is the number of users who have created accounts in the given month, active_m0 – number of users who made first purchase in the same month as they registered, active_m1 – number of users who made first purchase in the following month, and so forth.

A: Assuming your input data in in the following format
dd<-structure(list(signup_date = structure(c(14955, 14977, 14941,
14979, 14923, 14938), class = "Date"), purchase_date = c(7L,
4L, 6L, 19L, 26L, 11L), nbr_purchase = c(2L, 1L, 2L, 9L, 3L,
2L)), .Names = c("signup_date", "purchase_date", "nbr_purchase"
), row.names = c(NA, -6L), class = "data.frame")

Then you can do
dd$cohort <- strftime(dd$signup_date, "%Y-%m")
dd$interval <- paste0("active_m",(dd$purchase_date %/% 10) +1)

tt<-with(dd, table(cohort, interval))
cbind(tt, signed_up=rowSums(tt))

to get the data you need
        active_m1 active_m2 active_m3 signed_up
2010-11         1         1         1         3
2010-12         1         0         0         1
2011-01         1         1         0         2

note that here I used 10 day intervals rather than 30 day since you didn't have any purchase observations that were over 30 days from signup. So for your real data, change %/% 10 to %/% 30.


text:
Q: spyder kernel error: an error ocurred while starting the kernel I bought a new computer and installed windows 11. I installed it on my computer by following the Windows Native part on the Tensorflow site step by step. I verified the GPU setup and it returned me this:
[PhysicalDevice(name='/physical_device:GPU:0', device_type='GPU')]

So as far as I understand, the installation seemed to be successful. When I wanted to train a working model that I wrote on my old computer, after training for about 15 minutes, it gave a message that "kernel is dead". If I didn't turn spyder off and on, I couldn't run my code again. I have repeatedly uninstalled and installed from my computer, tried different ways, but got the same result in all of them. I've been trying to fix it for 3 days but I haven't made any progress. Please help me.
The last time I installed and tried the lower version of anaconda, again after training the model for a while, this is the error I got:
2023 18:28:56.450212: I tensorflow/core/platform/cpu_feature_guard.cc:193] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance‑critical operations: AVX AVX2
To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
2023 18:28:57.006390: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1616] Created device /job:localhost/replica:0/task:0/device:GPU:0 with 1641 MB memory: ‑> device: 0, name: NVIDIA GeForce RTX 3050 Ti Laptop GPU, pci bus id: 0000:01:00.0, compute capability: 8.6
2023 18:30:35.689718: I tensorflow/stream_executor/cuda/cuda_blas.cc:1614] TensorFloat will be used for the matrix multiplication. This will only be logged once.


text:
Q: make the listview receive two texts I'm using fragment Hi guys I have problem.......
I have created fragment activity using viewpager with two tabs,and created listview with two textviews, I want to sent the to texts from tab one to tab two as title and description,I have successfully sent the description but failed to send the title(just I can send only one text) do I need (Getter()/Setter()) ? How to do one??
my fragment_one.java :
public class FragmentOne extends Fragment {
SendMessage SM;
ViewPager viewPager;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View rootView = inflater.inflate(
            R.layout.fragment_one, container, false);
    return rootView;

}

@Override
public void onViewCreated(final View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    viewPager = (ViewPager)view.findViewById(R.id.viewPager);
    Button btnPassData = (Button) view.findViewById(R.id.btnPassData);

    final EditText inData = (EditText) view.findViewById(R.id.inMessage);
    btnPassData.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            SM.sendData(inData.getText().toString().trim());
        }
    });

}

interface SendMessage {
    void sendData(String message);
}

@Override
public void onAttach(Context context) {
    super.onAttach(context);

    try {
        SM = (SendMessage) getActivity();
    } catch (ClassCastException e) {
        throw new ClassCastException("Error in retrieving data. Please try again");
    }
}

}
my fragment_two.java :
public class FragmentTwo extends Fragment {

ListView listView;
ArrayList<String> arrayList = new ArrayList<>();
ArrayAdapter<String> adapter;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View rootView = inflater.inflate(
            R.layout.fragment_two, container, false);
    return rootView;

}

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    listView = (ListView) view.findViewById(R.id.list_view);
    adapter = new ArrayAdapter<String>(getActivity(), R.layout.single_item,R.id.tvdesc, arrayList);

    listView.setAdapter(adapter);
}

protected void displayReceivedData(String message) {
    arrayList.add(0,message);
    adapter.notifyDataSetChanged();

}

}
my custom_items.xml :
<TextView
    android:id="@+id/tvtitle"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="5dip"
    android:layout_toLeftOf="@+id/tvdate"
    android:layout_toRightOf="@+id/image"
    android:maxLines="1"
    android:text="title"
    android:textColor="@android:color/black"
    android:textSize="15dip"
    android:textStyle="bold" />

<TextView
    android:id="@+id/tvdesc"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/tvtitle"
    android:layout_toRightOf="@+id/image"
    android:ellipsize="end"
    android:maxLines="3"
    android:text="desc"
    android:textColor="@android:color/black"
    android:textSize="13dip"
    android:lines="3" />

<TextView
    android:id="@+id/tvdate"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_marginRight="5dp"
    android:layout_marginTop="5dip"
    android:text="date"
    android:textColor="@android:color/black"
    android:textSize="12dip" />

note: I have asked this question many times but nobody has helped me, so you would not put any link to another question if you know the answer helped me or ignore this question.

A:
make your SendMessage interface like this

 interface SendMessage {
    void sendData(String title,String message);
}

Now send both title and message to another fragment using bundle.
I think it will be helpful to you


text:
Q: elasticsearch deletebyquery return only not found I try use https://www.npmjs.com/package/elasticsearch-deletebyquery for delete documents by query. But all time returned me No found.  My usage :
client.deleteByQuery({
  index: index,
  type: type,
  body: {
    query: {
      range: {
        timeStamp: {
          gte: "2016-03-05",
          lt: "2016-03-06"
        }
      }
    }
  }
});

On return i have:
Elasticsearch TRACE: 2016-03-05T11:48:52Z
  -> DELETE ... 9200/amazontest/pageRanktest/_query
  {
    "query": {
      "range": {
        "timeStamp": {
          "gte": "2016-03-05",
          "lt": "2016-03-06"
        }
      }
    }
  }
  <- 404
  {
    "found": false,
    "_index": "amazontest",
    "_type": "pageRanktest",
    "_id": "_query"

What's wrong? Can anyone please help me?

A: As of ES 2.0, the delete-by-query feature has been removed from the core and is now available as a plugin. You can install the delete-by-query plugin on all your ES nodes in order to add support for deleting documents by query.
Install the plugin like this:
bin/plugin install delete-by-query

And then you can run your code without getting a 404.


text:
Q: What is the maximum value that can be generated by 6 random bytes in the crypto module? If I'm using parseInt(crypto.randomBytes(6).toString('hex'), 16);, what's the maximum value I can get?
My ultimate goal is to get a float value out of it (like Math.random() ), so I want to divide the result I get from parseInt(crypto.randomBytes(6).toString('hex'), 16); by the maximum value.

A: Each byte has a maximum value of 256, so with 6 bytes, the total maximum value is 256^6 - 1 which is 281,474,976,710,655. It's 1 less because you start counting from zero.


text:
Q: MFC + Wininet + proxy authentication = problems I have some code (its actually for sending SMS messages via a web interface, but that's not relevant). The code works fine in the absence of a proxy server, but one customer wants to use this configuration. I've been testing with our proxy, but can't get it working. When slogging through the help, I found MSKB article 195650 (How To Handle Proxy Authorization with WinInet), which contains this pearl of wisdom:
There are several ways to handle HTTP_STATUS_PROXY_AUTH_REQ without
displaying a user interface. By far the easiest way to do this is by
using the InternetSetOption function with the flags
INTERNET_OPTION_PROXY_PASSWORD and INTERNET_OPTION_PROXY_USERNAME...

...The same functionality can be accomplished in an MFC application
by detecting HTTP_STATUS_PROXY_AUTH_REQ, calling
CHttpConnection::SetOption, then re-calling CHttpFile::SendRequest.

So I implemented this solution in my code, detecting the 407 error from a proxy requiring authentication, and then supplying the basic authentication via SetOption calls:
     if (AfxParseURL (m_csServerUrl, dwServiceType, csServerName, csObjectName, nPort))
     {
        CString csProxy = m_pOwner->GetProxyServerSetting();
        if (csProxy.GetLength() > 0)
        {
           pSession  = new CMyInternetSession (TEXT("SmGen"),
                                               1,
                                               INTERNET_OPEN_TYPE_PROXY,
                                               csProxy,
                                               NULL,
                                               INTERNET_FLAG_KEEP_CONNECTION);
        }
        else
        {
           pSession  = new CMyInternetSession (TEXT("SmGen"),
                                               1,
                                               INTERNET_OPEN_TYPE_PRECONFIG,
                                               NULL,
                                               NULL,
                                               0);
        }
        if (pSession)
        {
           pSession->SetOwnerDialog (m_pOwner);
           pHttpConn = pSession->GetHttpConnection (csServerName, (INTERNET_PORT)nPort, NULL, NULL);

           if (pHttpConn)
           {
              dwFlags = INTERNET_FLAG_RELOAD |
                        INTERNET_FLAG_DONT_CACHE;
              pHttpFile = pHttpConn->OpenRequest (CHttpConnection::HTTP_VERB_GET,
                                                  csObjectName + TEXT("?") + csHTTP,
                                                  NULL,
                                                  1,
                                                  NULL,
                                                  NULL,
                                                  dwFlags);
              if (pHttpFile)
              {
                 pHttpFile->AddRequestHeaders (csHeaders);

                 if (pHttpFile->SendRequest ())
                 {
                    pHttpFile->QueryInfoStatusCode (dwResult);
                    bRetryWithAuth = FALSE;

                    switch (dwResult)
                    {
                       case HTTP_STATUS_OK:
                          // log success
                          break;

                       case HTTP_STATUS_PROXY_AUTH_REQ:
                          bRetryWithAuth = TRUE;
                          break;

                       default:
                          // log failure
                          break;
                    }

                    if (bRetryWithAuth)
                    {
                       csProxyUsr = m_pOwner->GetProxyUsername();
                       csProxyPwd = m_pOwner->GetProxyPassword();

                       pHttpConn->SetOption (INTERNET_OPTION_PROXY_USERNAME,
                                             csProxyUsr.GetBuffer(1),
                                             csProxyUsr.GetLength());
                       csProxyUsr.ReleaseBuffer();

                       pHttpConn->SetOption (INTERNET_OPTION_PROXY_PASSWORD,
                                             csProxyPwd.GetBuffer(1),
                                             csProxyPwd.GetLength());
                       csProxyPwd.ReleaseBuffer();

                       if (pHttpFile->SendRequest ())
                       {
                          // ... TIMEOUT

Now for the problem. The issue is that the second SendRequest doesn't fail or throw another error, it just times out. After a little while I get CInternetException 12002 (timeout) thrown via my wrapper handler. This is a little annoying. Needless to say, the SMS never arrives.
The proxy server address is of the form a.b.c.d:8080 to eliminate DNS as a causative factor. My MIS department assures me that the username and password I'm supplying are valid (if I pass a bad uid/pwd it simply reverts to a 407 error, so I know they're getting to the proxy, at least).
I've been through everything I can find both on here and online, and I'm getting nowhere. Simply using INTERNET_OPEN_TYPE_PRECONFIG and hoping that the system will fetch everything it needs automagically doesn't work if all you have is a proxy, sadly.
Remember, there's nothing wrong with the non-proxy-related functionality of the code, because if I eliminate the proxy by wiping the registry entry that supplies the server ip:port, it all leaps into life again.
I'm completely stumped. Has anyone seen this before? I'm not hopeful, given the number of queries about proxy authentication with no replies...
Edit:
I've converted this code to use WinHttp, since there is an MS sample which covers proxy (with authentication), and WinInet is deprecated anyway. All works fine now.

A: Usually a HTTP connection is closed after the client received a response.
So by the time you send your second request with auth details the proxy will have closed the connection (or at least stopped receiving).
So you'll have to call OpenRequest again to establish a new connection.


text:
Q: Convergence of recursive sequence $x_n=\sqrt{x_{n-1}^2-x_{n-1}+1}$ where $0as you can see from the title I have a recursive sequence with the type above. I want to prove that this sequence converges. Although I have searched a lot for some related sequence, I haven't figured out how to prove that it is monotonous. Which is the preferred way of solving this?

A: Let $f(x)=\sqrt{x^2-x+1}$. The sequence can be written then as $x_n=f(x_{n-1})$.

On $(0,1)$ we have $x< f(x)<1$. From here it follows easily that $x_n>x_{n-1}$ and $x_n<1$ for all $n$.

A: It should read: $x_n=\sqrt{x_{n-1}^2-x_{n-1}+1}$ , where $ 0<x_0<1$.

*

*Show by induction: $0<x_n <1$ for all $n$.

*Show by induction: $(x_n)$ is increasing.

A: Ok, I think that I have a solution, first of all I showed that $0<x_1<1$ . Since $0<x_0<1$, this means that also $0<x_0^2<1$ and also that $x_0^2<x_0$ <=> $x_0^2-x_0<0$ <=> $x_0^2-x_0+1<1$, which means that $x_1=\sqrt{x_0^2-x_0+1}<1$. So in the same manner I proved that if $0<x_n<1$ then also $0<x_{n+1}<1$.
After that I showed that $x_{n+1}-x_n>0$, so $x_n$ is increasing until it reaches 1.

A:
I haven't figured out how to prove that it is monotonous

It is given that $0 \lt x_0 \lt 1\,$, and suppose by induction that $0 \lt x_{n-1} \lt 1\,$. Then:

*

*$$\require{cancel}
1 - x_n^2 = \cancel{1}-(x_{n-1}^2-x_{n-1}+\cancel{1})=x_{n-1}-x_{n-1}^2=x_{n-1}(1-x_{n-1}) \;\in\; (0,1)
$$

*$$
 x_n=\sqrt{x_{n-1}^2-2x_{n-1}+1+ x_{n-1}}=\sqrt{(x_{n-1}-1)^2+x_{n-1}} \gt \sqrt{x_{n-1}} \gt x_{n-1}
$$
Therefore $0 \lt x_n \lt 1$ and $x_n \gt x_{n-1}\,$, which completes the induction step and proves both monotonicity and boundedness to $(0,1)\,$.


text:
Q: Linq for getting words in sentences I have a List of words and a List of sentences.
I want to know which words can be found in which sentences.
Here is my code:
List<string> sentences = new List<string>();
List<string> words = new List<string>();

sentences.Add("Gallia est omnis divisa in partes tres, quarum unam incolunt Belgae, aliam Aquitani, tertiam qui ipsorum lingua Celtae, nostra Galli appellantur.");
sentences.Add("Alea iacta est.");
sentences.Add("Libenter homines id, quod volunt, credunt.");

words.Add("est");
words.Add("homines");

List<string> myResults = sentences
  .Where(sentence => words
     .Any(word => sentence.Contains(word)))
  .ToList();

What i need is a list of Tuples. With the sentence and the word, that was found in the sentence.

A: First, we have to define what is word. Let it be any combination of letters and apostrophes.
  Regex regex = new Regex(@"[\p{L}']+");

Second, we should think over on what shall we do with case. Let's implement case insensitive routine:
  HashSet<string> wordsToFind = new HashSet<string>(StringComparer.OrdinalIgnoreCase) {
    "est",
    "homines"
  };

Then we can use Regex to match words in the sentences, and Linq to query the sentences:
Code:
  var actualWords = sentences
    .Select((text, index) => new {
      text = text,
      index = index,
      words = regex
        .Matches(text)
        .Cast<Match>()
        .Select(match => match.Value)
        .ToArray()
    })
    .SelectMany(item => item.words
       .Where(word => wordsToFind.Contains(word))
       .Select(word => Tuple.Create(word, item.index + 1)));

  string report = string.Join(Environment.NewLine, actualWords);

  Console.Write(report);

Outcome:
  (est, 1)         // est appears in the 1st sentence
  (est, 2)         // est appears in the 2nd sentence as well
  (homines, 3)     // homines appears in the 3d sentence

If you want Tuple<string, string> for word, sentence, just change Tuple.Create(word, item.index + 1) for Tuple.Create(word, item.text) in the last Select

A: Do you just mean this:
IEnumerable<(string, string)> query =
    from sentence in sentences
    from word in words
    where sentence.Contains(word)
    select (sentence, word);

That gives:

A: You can try this way,
var result = from sentence in sentences
             from word in words
             where sentence.Contains(word)
             select Tuple.Create(sentence, word);


text:
Q: Convert inline plugin webpack 4 to webpack 5 For my project, I was using webpack 4 with Karma to run my test. Everything was working fine.
And I successfully migrate to webpack 5.
However, I had a custom inline plugin that I found on GitHub and I don't know how to convert it to make it work on webpack 5.
webpack.config
// ...
plugins: [
    // ...
    function()
    {
        this.plugin("done", function(stats)
        {
            if (stats.compilation.errors && stats.compilation.errors.length && process.argv.indexOf('--watch') == -1)
            {
                console.log(stats.compilation.errors);
                process.exit(1); // or throw new Error('webpack build failed.');
            }
            // ...
        });
    }
    // ...
],
// ...

Indeed, I have this error on webpack 5:

09 03 2021 01:56:20.991:ERROR [karma-server]: Error during file loading or preprocessing

TypeError: this.plugin is not a function

A: I think you can follow up the official document then it would work normally.
BTW, your code should potentially be changed to:
{
  // ...
  plugins: [
    new class YourPlugin {
      apply(compiler) {
        compiler.hooks.done.tap('YourPlugin', (
          stats
        ) => {
          if (
            stats.compilation.errors &&
            stats.compilation.errors.length && process.argv.indexOf('--watch') == -1
          ) {
            console.log(stats.compilation.errors);
            process.exit(1); // or throw new Error('webpack build failed.');
          }
        });
      }
    }
  ]
}


text:
Q: Parsing strings containing variable names in Delphi I'm currently writing an application in which I have a function as follows:
var a,b,c, algorithm: string
begin

a := some-operations-with-regular-expressions;
b := some-other-operation-with-regular-expressions;
c := just-similar-to-b-but-different;

algorithm := IniFile.ReadString('XML Info','AlgorithmExpression', '');
//algorithm is fetched like 'http://wwww.urlhere' + a + '/' + b + '/' + c
DoDownload (algorithm, true);
end;

Now what I expected was to have a, b & c automatically replaced with the values of the variables with the same name, but it appears that I'm so wrong. Is there any way to get the result of the algorithm variable composed of the strings between '' and the variable values?
Any suggestion (even if it calls for major redesigning) would be much appreciated.
Thanks,
sphynx

A: If this is about formatting, Delphi also has the C style format command:
var
  output: String;
begin
  output := Format('http://%s/%s/%s', ['this', 'that', 'otherthing']);
  ShowMessage(output);
end;

Shows the message:

http://this/that/otherthing

A: I didn't understand what you are trying to do, but here goes a shot.
IniFile should contain something like this:
[XML Info]
AlgorithmExpression=http://wwww.urlhere[<a>]/[<b>]/[<c>]

and you could do something like this:
algorithm := IniFile.ReadString('XML Info','AlgorithmExpression', '');
algorithm := StringReplace(algorithm,'[<a>]',a,[]);
algorithm := StringReplace(algorithm,'[<b>]',b,[]);
algorithm := StringReplace(algorithm,'[<c>]',c,[]);
DoDownload (algorithm, true);


text:
Q: Javascript implicit parameter names for lambdas Does Javascript/ES8 have shorthand argument names, like Swift?
eg. arr.sort { $0.name > $1.name }

A: There are no shorthand arguments in Javascript. The closest alternatives are arguments and ES6 rest parameter.
function fn(param1, param2) {
  const $ = arguments;

  // by name
  console.log(param1, param2);

  // by order
  console.log($[0], $[1]);
}

Rest parameter it is more consistent than arguments, the latter isn't supported in arrow functions:
const fn = (...$) => {
  // by name
  let [param1, param2] = $;
  console.log(param1, param2);

  // by order
  console.log($[0], $[1]);
}

Notice that $ parameter name is used to draw an analogy to Swift. It is not recommended to use $ name in practice because it may be confused with conventional jQuery $ variable. The conventional meaningful name for rest parameter that includes all arguments is args.

A: No, javascript doesn't support shorthand argument name.


text:
Q: Word sequence using apriori I have implemented Apriori to find the repeating sequence of letters but what i want to do is find the repeating words. My output gives me all the letters count. But, i want the word count;
i/p
    data = ["i am donald trump","i am donald duck"]
o/p
    --> {'d ': 3, ' d': 3, 'on': 3, 'ld': 3, 'am': 3, 'do': 3, 'al': 3, 'na'}
-->what i wanted ->
 i: 2
am: 2
trump: 2
donald: 3
i am: 2
am donald: 2
donald trump: 1
i am donald: 2
import re
import unittest
from collections import defaultdict
import itertools

class Apriori(dict):

    def __init__(self, listOfSequences, support):

        Args:
            listOfSequences (list): A list of strings, each letter representing a specific event.
            support (int): The minimum percentage of sequences a pattern must match.
        """

        super(Apriori, self).__init__()
        self.data = listOfSequences
        self.thres = (support * len(self.data)) / 100.0
        self.primitives = self.getPrimitives()
        self.apriori()
        del self.data

    def apriori(self):
        candidates = self.getNewCandidates(self.primitives)
        while len(candidates) > 0:
            res = self.getPatternsCount(candidates)
            self.update(res)
            candidates = self.getNewCandidates(res.keys())

    def getPrimitives(self):
        primitives = set()
        for seq in self.data:
            for event in seq:
                primitives.add(event)
        return primitives

    def getNewCandidates(self, candidates):
        newCandidates = set()
        for seq in self.data:
            for can in candidates:
                for subs in re.findall(can + ".", seq):
                    newCandidates.add(subs)
        return newCandidates

    def getPatternsCount(self, candidates):
        patternsCount = defaultdict(int)
        for seq in self.data:
            for can in candidates:
                if can in seq:
                    patternsCount[can] += 1
        return {k: v for k, v in patternsCount.items() if v > self.thres}

    if __name__ == '__main__':
        pass

Run:
import csv
from ne import *

#print(t)
data = ["i am donald trump","i am donald duck"]
#print(data.type())

patterns= Apriori(data,15)

print(patterns)

A: Focusing on your specific question (and ignoring some issues in your posted code), you can achieve what you want by simply splitting the input strings and maintaining frequency counts for those split tokens.
For example, using Counter:
from collections import Counter

data = ["i am donald trump","i am donald duck"]
c = Counter()
for seq in data:
    c += Counter(seq.split(' '))

print c  # Counter({'i': 2, 'donald': 2, 'am': 2, 'trump': 1, 'duck': 1})

p.s. And then you probably won't be interested in the most_common values, but in those that surpassed a certain threshold, like:
print {(k,v) for k,v in c.iteritems() if v >= 2}  # {('am', 2), ('donald', 2), ('i', 2)}


text:
Q: Can I safely store UInt32 to NSInteger? Is an NSInteger big enough for UInt32? Or is it even the same thing?

A: No because NSInteger is a signed type while UInt32 is unsigned.
You should inspect the definitions of these types in Apple's header files to understand what they mean. It's very easy to do so. From an open project in Xcode, select File -> Open Quickly... (Command-Shift-D) and type the type name you are interested in into the text field. It will find the file where it is defined. Or just Command-double click a type in your source code.

A: Here is code from NSObjCRuntime.h (from the iPhone SDK 3.2 install):
#if __LP64__ || (TARGET_OS_EMBEDDED && !TARGET_OS_IPHONE) || TARGET_OS_WIN32 || NS_BUILD_32_LIKE_64
typedef long NSInteger;
typedef unsigned long NSUInteger;
#else
typedef int NSInteger;
typedef unsigned int NSUInteger;
#endif


text:
Q: iTunes cannot convert Apple Lossless tracks to 128 kbps AAC files when sync'ing with iPhone I'm using the Convert higher bit rate songs to 128 kbps AAC option in iTunes when sync'ing music to my iPhone.
iTunes is complaining about three tracks from an album I recently ripped every time I sync my phone. It claims they can't be converted (I rip as Apple Lossless). Unfortunately there's not much in the way of detailed information in the error messages iTunes is giving me.
Does iTunes maintain a parallel, down-sampled, library on disk when I check this option? Could I downsample my Apple Lossless files myself, save them in this parallel library, and stop iTunes from trying to do the conversion on sync? I took a look in my iTunes Media folder for a parallel library but couldn't find anything.
Is the conversion done as the songs are transferred to my iPhone and the converted files live no other place than on my phone?
This is iTunes 10 on OS X 10.6 with an iPhone 3GS.

A: I had a similar problem with few of my tracks. The conversion is done live, while syncing. Basicly the problem is with the particular sound track, not the lossless codec (ALAC) itself. I used a third party utility to re-encode the original (keeping it to ALAC) and then iTunes managed to re-encode the track back to 128kBit AAC. Hope this helps.

Does iTunes maintain a parallel, down-sampled, library on disk when I check this option?

No - re-encoding is done live, that's why it's so slow.

A: I just had this problem too, and it fixed itself when:

*

*I went to the Music/Songs view and searched for the offending song.

*I noticed there were 2 copies of that song listed: one in my library, and one with an iTunes-Store download icon next to it

*I clicked on that download icon and deleted the copy in my library.

Upon re-syncing my iPhone, that song copied without issue.

A: I had two songs that did not work. One could be fixed by "remove download" and then pressing the cloud symbol and redownload the song. The other one is still problematic and me be it has to be recoded. I guess apple repaired one of the songs.


text:
Q: How to define an instance depending on some variable? I'll give code on Python, but it's doesn't matter.
I have a module argument_parser with dictionary and class:
FORMATS = {
    'JSON': 'json',
    'XML': 'xml',
}

class ArgumentParser:
    # some methods
    def parse():
        """returns 'XML' or 'JSON' string"""
        return fomat

and a module with presenters -- presenter
class JSONPresenter:
    # some magic

class XMLPresenter:
    # some magic

The problem is in dependency injection:
argument_parser = ArgumentParser()
format = argument_parser.parse()

if format == argument_parser.FORMATS['JSON']:
    presenter = JSONFilePresenter()
elif format == argument_parser.FORMATS['XML']:
    presenter = XMLFilePresenter()

if-elif construction is ugly. If I want to add some other formats I'll must add more elif.
I could define the type of presenter in ArgumentParser class but I think semantically it is wrong -- it is not a filed of responsibility of this class. What should I do to do it right?

A: PRESENTERS = {
    'json': JSONPresenter(),
    'xml': XMLPresenter(),
}

argument_parser = ArgumentParser()
fmt = argument_parser.parse()
presenter = PRESENTERS[fmt]

Or, if you need a new presenter every time:
PRESENTERS = {
    'json': lambda: JSONPresenter(),
    'xml': lambda: XMLPresenter(),
}

argument_parser = ArgumentParser()
fmt = argument_parser.parse()
presenter = PRESENTERS[fmt]()


text:
Q: Notification firing more than once a day My alarmManager seems to be firing a notification once an hour , instead of once a day. I would like my app to fire a notification once a day , where the user will click on the notification and be taken to a new activity where they will learn a new word/definition.
I did not include the Word.class and Definition.class, I think the problem may have to do wuth the definition class, there is no "exit" the only option is to hit the home button or go back
package com.example.awordaday;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;

public class MyAlarmService extends Service {

// private NotificationManager mManager;

@Override
public IBinder onBind(Intent arg0) {
    // TODO Auto-generated method stub
    return null;
}

@Override
public void onCreate() {
    // TODO Auto-generated method stub
    super.onCreate();
}

@SuppressWarnings({ "static-access", "deprecation" })
@Override
public void onStart(Intent intent, int startId) {
    super.onStart(intent, startId);

    // mManager = (NotificationManager)
    //   this.getApplicationContext().getSystemService(this.getApplicationContext().NOTIFICATION_SERVICE);
    Intent intent1 = new Intent(this.getApplicationContext(), Word.class);// this
                                                                            // is
                                                                            // what
                                                                            // starts

    PendingIntent showWord = PendingIntent.getActivity(this, 0, intent1, 0);

    /*
     * Notification notification = new
     * Notification(R.drawable.ic_launcher,"Daily Word",
     * System.currentTimeMillis());
     * intent1.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP|
     * Intent.FLAG_ACTIVITY_CLEAR_TOP);
     */

    Notification notification = new NotificationCompat.Builder(this)
            .setTicker("Daily Word").setSmallIcon(R.drawable.ic_launcher)
            .setContentTitle("Daily Word")
            .setContentText("Your Word is ready")
            .setContentIntent(showWord).setAutoCancel(true).build();

    /*
     * PendingIntent pendingNotificationIntent = PendingIntent.getActivity(
     * this.getApplicationContext(),0,
     * intent1,PendingIntent.FLAG_UPDATE_CURRENT); notification.flags |=
     * Notification.FLAG_AUTO_CANCEL;
     * notification.setLatestEventInfo(this.getApplicationContext(),
     * "Daily Word" , "Your Word is ready", pendingNotificationIntent);
     */

    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    notificationManager.notify(0, notification);

    // mManager.notify(0, notification);

}

@Override
public void onDestroy() {
    // TODO Auto-generated method stub
    super.onDestroy();
  }

}

package com.example.awordaday;

import java.util.Calendar;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.text.format.Time;

public class MainActivity extends Activity {

private PendingIntent pendingIntent;

@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    // setContentView(R.layout.activity_main);

    Calendar calendar = Calendar.getInstance();

    /*
     * time to set alarm calendar.set(Calendar.MONTH, 6);
     * calendar.set(Calendar.YEAR, 2013);
     * calendar.set(Calendar.DAY_OF_MONTH, 13);
     */

    calendar.set(Calendar.HOUR_OF_DAY, 9);
    calendar.set(Calendar.MINUTE, 21);
    calendar.set(Calendar.SECOND, 00);
    calendar.set(Calendar.AM_PM, Calendar.PM);

    Intent myIntent = new Intent(MainActivity.this, MyReceiver.class);
    pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0,
            myIntent, 0);
    // year day
    // added this
    AlarmManager alarmManager = (AlarmManager) this
            .getSystemService(ALARM_SERVICE);
    // alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(),
    // pendingIntent);
    alarmManager.setRepeating(1, calendar.getTimeInMillis(),
            AlarmManager.INTERVAL_DAY, pendingIntent);

  } // end onCreate
}

A: Here are one example of using RTC.
Fire the alarm at approximately 21:21, and repeat once a day at the same time:
// Set the alarm to start at approximately 09:21 p.m.
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 21);
calendar.set(Calendar.MINUTE, 21);

// With setInexactRepeating(), you have to use one of the AlarmManager interval
// constants--in this case, AlarmManager.INTERVAL_DAY.

alarmMgr.setInexactRepeating(AlarmManager.RTC, calendar.getTimeInMillis(),
        AlarmManager.INTERVAL_DAY, alarmIntent);

documentation


text:
Q: numpy image replace areas with equal values So I have a gray (2D) image of type np.array with a lot of zeros and objects inside of it. Each object is defined by its pixels having the same value, e.g. 1.23e15.
I now want to label the image, i.e. I want to rescale all pixels of a certain value (eg 200 pixels of the above value 1.23e15) to one integer number.
Apart from the background which is zero, I want each region to be set to one of the values in range(1,nbr_of_regions_in_img+1).
How can I do this time efficiently (I have hundreds of thousands of images) without the obvious looping solution?

A: Scipy has an extensive library for image manipulation and analysis. The function, you are looking for is probably scipy.ndimage.label
import scipy.ndimage
import numpy as np

pix = np.array([[0,0,1,1,0,0],
                [0,0,1,1,1,0],
                [1,1,0,0,1,0],
                [0,1,0,0,0,0]])
mask_obj, n_obj = scipy.ndimage.label(pix)

The output gives you both, a labelled mask with a different number for each identified object and the number of identified objects.
>>>print(n_obj)
>>>2
>>>print(mask_obj)
>>>[[0 0 1 1 0 0]
    [0 0 1 1 1 0]
    [2 2 0 0 1 0]
    [0 2 0 0 0 0]]

You can also define, what should count as a neighbouring cell with the structure parameter:
s = np.asarray([[1,1,1],
                [1,1,1],
                [1,1,1]])

mask_obj, n_obj = scipy.ndimage.label(pix, structure = s)
>>>print(n_obj)
>>>1
>>>print(mask_obj)
>>>[[0 0 1 1 0 0]
    [0 0 1 1 1 0]
    [1 1 0 0 1 0]
    [0 1 0 0 0 0]]

Difficulties will arise, if different objects touch each other, i.e. they are not separated by a zero value.


text:
Q: Can Assets/Resoures be shared between iOS + Droid projects? I have a Xamarin based Visual Studio 2015 project that has the following structure.
MyApp (Portable)
MyApp.Droid
MyApp.iOS
Currently I include assets / resources in the MyApp.Droid project and the MyApp.iOS project.
So for example myhtml.html is duplicated as both MyApp.Droid/Asserts/myhtml.html and MyApp.iOS/Resources/myhtml.html
Are there any ways I can avoid this duplication?

A: Assuming you are using Xamarin Forms, yes, you can use .net resource files.
You can create a folder in the portable project, add there the content files and set the Compilation Action to Embedded Resource for all of those, then you can use the .net provided mechanism to acces the resources, per example (in this example I assume the code is being executed in a class contained in the portable project and the files are stored in a folder called ResourceFiles):
var htmlFile = this.GetType().GetTypeInfo().Assembly.GetManifestResourceStream("MyNamespace.ResourceFiles.myhtml.html");

In this way you have the stream with the file's content.
Also, as a hint, you can load these files from XAML using a custom markup extension, per example, here is a markup extension to load images from .net resources:
[ContentProperty ("Source")]
public class ImageResourceExtension : IMarkupExtension
{
    public string Source { get; set; }

    public object ProvideValue (IServiceProvider serviceProvider)
    {
        if (Source == null)
            return null;

        var imageSource = new StreamImageSource { Stream = async (ct) => this.GetType().GetTypeInfo().Assembly.GetManifestResourceStream(Source) };

        return imageSource;
    }
}

Then, to use this extension in XAML you will do (local is the XAML namespace definition of your own namespace):
<Image Source="{local:ImageResource MyNamespace.ResourceFiles.MyImage.png}" />


text:
Q: Using physical disks from old RAID NAS I had a WD MyCloud EX4100 NAS device with four 4TB SATA disks configured in a RAID 5 array (so, 16TB capacity, less overhead).
A lightning strike rendered the device inoperable. It will not boot.
The insurance company has replaced the NAS device with a new one. It is identical in every way (except perhaps firmware level), as the old device was only a year or so old.
I would like to replace the four blank disks in the new device with the four disks from the old one. I am assuming that the existing disks were not damaged by the lightning strike, only the NAS electronics.
Of course, I will respect the positioning of the physical drives in the array -- I'll put the drive from old slot 1 into new slot 1, etc.
If my assumption is correct that the physical drives were not damaged, should I be able to access my data on the new NAS device? Are there any settings I should make or other procedures I should follow before transferring the drives?
For bonus credit: To maximize the selling price, should I sell the four new, blank drives separately, or as a set of four?

A: I figured this out. Migrating physical disks from one WD MyCloud 4100 enclosure to another is a supported process called RAID Roaming. The steps to follow are detailed here, in an official WD support article.
I followed the steps, and everything worked fine. All my old partitions and data are visible. I just had to update the firmware settings to match what I had before -- set the device name, set users and permissions, things like that.