text:
Q: Java - execute a program with options, like ls -l
*

*In Java, how do I execute a linux program with options, like this:
ls -a (the option is -a),
and another: ./myscript name=john age=24
I know how to execute a command, but cannot do the option.

A: You need to execute an external process, take a look at ProcessBuilder and just because it almost answers your question, Using ProcessBuilder to Make System Calls
UPDATED with Example
I ripped this straight from the list example and modified it so I could test on my PC and it runs fine
private static void copy(InputStream in, OutputStream out) throws IOException {
    while (true) {
        int c = in.read();
        if (c == -1) {
            break;
        }
        out.write((char) c);
    }
}

public static void main(String[] args) throws IOException, InterruptedException {

//        if (args.length == 0) {
//            System.out.println("You must supply at least one argument.");
//            return;
//        }

    args = new String[] {"cmd", "/c", "dir", "C:\\"};

    ProcessBuilder processBuilder = new ProcessBuilder(args);
    processBuilder.redirectErrorStream(true);

    Process process = processBuilder.start();
    copy(process.getInputStream(), System.out);
    process.waitFor();
    System.out.println("Exit Status : " + process.exitValue());
}

A: Apache Commons has a library built to handle this type of thing. I wish I knew about it before I coded something like this by hand. I found it later on. It takes options in various formats for a command line program.
Apache Commons CLI


text:
Q: PowerShell get-child item and get-content a few folders deep My script below only works for 1 folder using the "$_" before prior to the location of the file:
get-childitem E:\WebSystems\Configs\ | Foreach-Object {get-content E:\WebSystems\Configs\$_\Web.config} | foreach-object {$_ -replace "Web1", "Web2"} | set-content E:\WebSystems\Configs\$_\Web.config}

How about two folders deep? ex: E:\WebSystems\Configs\Folder1\Folder2\Web.config
The following script doesn't work.
get-childitem E:\WebSystems\Configs\ | Foreach-Object {get-content E:\WebSystems\Configs\$_\$_\Web.config} | foreach-object {$_ -replace "Web1", "Web2"} | set-content E:\WebSystems\Configs\$_\$_\Web.config}

A: This should work:
get-childitem -recurse -include Web.Config | foreach-object { $name = $_.FullName; get-content $name } | foreach-object {$_ -replace "Web1", "Web2" } | set-content $name

I implore you to test this on an isolated temporary directory. You might want to try this at first:
get-childitem -recurse -include Web.Config | foreach-object { $name = $_.FullName; get-content $name } | foreach-object {$_ -replace "Web1", "Web2" } | set-content "$name.modified"

redpajama_set_name: RedPajamaStackExchange


text:
Q: Deleting text from an edit control in Python 2.7? How can I program the example below to delete all contents from the  Edit box?  (this is example is taken from http://www.java2s.com/Code/Python/GUI-Tk/SimpleEditor.htm)
My guess is that one must select all the contents and then do some sort of .tag_remove(SEL, '1.0', END)  but I can't find the commands to program it to select all the text.
from Tkinter import *
from tkSimpleDialog import askstring
from tkFileDialog   import asksaveasfilename

from tkMessageBox import askokcancel

class Quitter(Frame):
    def __init__(self, parent=None):
        Frame.__init__(self, parent)
        self.pack()
        widget = Button(self, text='Quit', command=self.quit)
        widget.pack(expand=YES, fill=BOTH, side=LEFT)
    def quit(self):
        ans = askokcancel('Verify exit', "Really quit?")
        if ans: Frame.quit(self)

class ScrolledText(Frame):
    def __init__(self, parent=None, text='', file=None):
        Frame.__init__(self, parent)
        self.pack(expand=YES, fill=BOTH)
        self.makewidgets()
        self.settext(text, file)
    def makewidgets(self):
        sbar = Scrollbar(self)
        text = Text(self, relief=SUNKEN)
        sbar.config(command=text.yview)
        text.config(yscrollcommand=sbar.set)
        sbar.pack(side=RIGHT, fill=Y)
        text.pack(side=LEFT, expand=YES, fill=BOTH)
        self.text = text
    def settext(self, text='', file=None):
        if file:
            text = open(file, 'r').read()
        self.text.delete('1.0', END)
        self.text.insert('1.0', text)
        self.text.mark_set(INSERT, '1.0')
        self.text.focus()
    def gettext(self):
        return self.text.get('1.0', END+'-1c')

class SimpleEditor(ScrolledText):
    def __init__(self, parent=None, file=None):
        frm = Frame(parent)
        frm.pack(fill=X)
        Button(frm, text='Save',  command=self.onSave).pack(side=LEFT)
        Button(frm, text='Cut',   command=self.onCut).pack(side=LEFT)
        Button(frm, text='Paste', command=self.onPaste).pack(side=LEFT)
        Button(frm, text='Find',  command=self.onFind).pack(side=LEFT)
        Quitter(frm).pack(side=LEFT)
        ScrolledText.__init__(self, parent, file=file)
        self.text.config(font=('courier', 9, 'normal'))
    def onSave(self):
        filename = asksaveasfilename()
        if filename:
            alltext = self.gettext()
            open(filename, 'w').write(alltext)
    def onCut(self):
        text = self.text.get(SEL_FIRST, SEL_LAST)
        self.text.delete(SEL_FIRST, SEL_LAST)
        self.clipboard_clear()
        self.clipboard_append(text)
    def onPaste(self):
        try:
            text = self.selection_get(selection='CLIPBOARD')
            self.text.insert(INSERT, text)
        except TclError:
            pass
    def onFind(self):
        target = askstring('SimpleEditor', 'Search String?')
        if target:
            where = self.text.search(target, INSERT, END)
            if where:
                print where
                pastit = where + ('+%dc' % len(target))
               #self.text.tag_remove(SEL, '1.0', END)
                self.text.tag_add(SEL, where, pastit)
                self.text.mark_set(INSERT, pastit)
                self.text.see(INSERT)
                self.text.focus()

if __name__ == '__main__':
    try:
        SimpleEditor(file=sys.argv[1]).mainloop()
    except IndexError:
        SimpleEditor().mainloop()

A: The text widget has a delete method, which you can use to delete characters. You don't need to select the characters first.
If you want to delete all of the text, just do:
self.text.delete("1.0", "end")

(you can also use a tkinter constant instead of the string "end", but I don't see the point)


text:
Q: GNU Radio : UDP stream data converter I have an external device, which sends UDP unicast packet of size 556 bytes. I need to transform each packet to vector of size 270 with uint16 inside. And then I'd like to plot this waveform as time-domain data. Here is a c++ code to do this tranformation :
 std::vector<boost::uint8_t> rxPacket(BUFFSIZE*sizeof(std::int16_t) + UPP_TAIL_SIZE_IN_BYTES, 0);

 udpBuffer->pop_back(rxPacket);

 std::vector<boost::int16_t> rx_data(BUFFSIZE, 0);

 memcpy(&rx_data[0], &rxPacket[0], BUFFSIZE*sizeof(std::int16_t));

How to do this using GNU Radio Companion? What block do I have to use to achieve this kind of transformation?

A: Nothing; you literally don't need to do anything – GNU Radio doesn't care about the actual data type, just the memory size of items.


text:
Q: Django tastypie advanced filtering I'm trying to implement an advanced filter in my Resource but i need some help to built and apply my own filters.
The goal is to get filters info in my api UserResource before to get objects list through an url like this:
http://127.0.0.1:8000/api/users/list/&orderby="gender"&limit=10

Actually, my resource looks like this:
class UserResource(Resource):

   firstName = fields.CharField(attribute='firstName')
   lastName = fields.CharField(attribute='lastName')
   gender= fields.CharField(attribute='gender')
   status= fields.IntegerField(attribute='status')
   date= fields.DateTimeField(attribute='date')

   class Meta:
       resource_name = 'users/list'
       object_class = dict2obj
       authorization = Authorization()

   def detail_uri_kwargs(self, bundle_or_obj):
       kwargs = {}
       if isinstance(bundle_or_obj, Bundle):
           kwargs['pk'] = bundle_or_obj.obj.firstName
       else:
           kwargs['pk'] = bundle_or_obj.firstName
       return kwargs

   def obj_get_list(self, request=None, **kwargs):
       db = MySQLdb.connect(host='xxx.xxx.xxx',user='test2',passwd='xxx',db='mydb')
       cur = db.cursor()
       cur.execute("SELECT * FROM users order by gender Desc limit 0,10")
       users=cur.fetchall()
       #...
       db.close()
       return posts

I would like to know how to get filters info to return my obj list.


text:
Q: No intellisense ("no definition found") for local JS dependencies even though they are fully typed Problem: When importing from node_modules in mycode.js, some modules are fully typed and intellisense is available, while others don't get that luxury.
E.g., when I press F12 with cursor on any file in src, it works.
E.g., when I press F12 with cursor on 'lodash/minBy', it also takes me to the correct type definition file (which is in a global node_modules folder for some reason, even though, I have it installed locally).
But when I press F12 with cursor on 'sigma', it complains "No definition found", as illustrated in this screenshot:
Naturally, lodash has full typing and intellisense support, while Sigma does not.
I already changed my jsconfig.json's include settings like so, but it did not help:
{
  "compilerOptions": {
    "module": "esnext",
    "target": "esnext",
    "checkJs": false,  /* Typecheck .js files. */
    "baseUrl": "./"
  },
  "include": [
    "src",
    "src/**/*",
    "../node_modules/sigma",
    "../node_modules/sigma/**/*",
    "../node_modules/graphology",
    "../node_modules/graphology/**/*"
  ]
}

The project is a mono-repo. My paths are:
root/some-package/jsconfig.json
root/some-package/src/mycode.js
root/node_modules/{sigma,graphology,etc.}


text:
Q: Facebook access_token failure from node.js I got this error while trying to get facebook access_token from node.js server:

{"error":{"message":"(#803) Some of the aliases you requested do not exist
  : access_token","type":"OAuthException","code":803}}

Following is the code for getting access_token:
var options={
        host:'graph.facebook.com',
        path:'oauth/access_token?client_id=MYAPPID&redirect_uri=http://127.0.0.1:8000/&client_secret=MYAPPSECRET&code=CODEOBTAINEDFROMFB'
}
http.get(options,function(res){
    res.on('data', function (chunk) {
        console.log('BODY: ' + chunk);
    });
});

Request for the same url from my browser is working fine and I am getting the access_token also. what is the prob here?
Update
This may be the most funniest thing I have experienced from node.js. I have updated the above code as:
var http=require('http')
var options={
        host:'grah.facebook.com',
        pathname:'/oauth/access_token',
        search:'client_id=MYAPPID&redirect_uri=http://127.0.0.1:8000/&client_secret=MYAPPSECRET&code=CODEOBTAINEDFROMFB'
}

http.request(options,function(res){
        console.log('http fb code')
         res.setEncoding('utf8');
    res.on('data', function (chunk) {
        console.log('BODY: '+chunk);
    });
});

And what happening is server throw an error called socket hang up. Also my network  connection(internet connected via mobile modem) breaks out immediately! While Googling this issue I found a lot similar to this, but can't find the perfect solution...

A: HTTP documentation lists path as option but states:

options align with url.parse()

You should use pathname (and search for query string) instead of path while creating your URL. Also see URL in documentation for node.js
var options={
  host:'graph.facebook.com',
  pathname:'oauth/access_token',
  search: 'client_id=MYAPPID&redirect_uri=http://127.0.0.1:8000/&client_secret=MYAPPSECRET&code=CODEOBTAINEDFROMFB'
}
http.get(options,function(res){
  res.on('data', function (chunk) {
    console.log('BODY: ' + chunk);
  });
});

Update:
In description of URL object in url.format() documentation doesn't list path as option so it's probably only returned by url.parse()
Node documentation on URL states:

path: Concatenation of pathname and search.

A: The problem is with http object. Facebook only allows https while requesting with client_secret.
so this can work as I expected:
var options={
        host:'graph.facebook.com',
        path:'/oauth/access_token?client_id=APPID&redirect_uri=http://127.0.0.1:8000/&client_secret=CLIENTSECRET&code=FBUSERCODE'
}
var https=require('https');
https.get(options,function(res){
        console.log('http fb code')
         res.setEncoding('utf8');
         res.on('data', function (chunk) {
                console.log('BODY: '+chunk);
        });
});


text:
Q: ktlint not checking kotlin file I want my project to perform ktlintCheck on all kotlin file, but it only check on build.gradle.kts file.
build.gradle.kts file as below
ktlint {
    version.set("9.4.0")
    debug.set(true)
    verbose.set(true)
    android.set(false)
    outputToConsole.set(true)
    reporters {
        reporter(ReporterType.PLAIN)
        reporter(ReporterType.CHECKSTYLE)
    }
    ignoreFailures.set(false)
    kotlinScriptAdditionalPaths {
        include(fileTree("src/"))
    }
    filter {
        exclude("**/generated/**")
        include("**/kotlin/**")
    }
}
subprojects {
    apply(plugin = "org.jlleitschuh.gradle.ktlint")
    ktlint {
        debug.set(true)
    }
}

When I run gradlew ktlintCheck, the Terminal output as below:
gradlew ktlintCheck

> Task :ktlintKotlinScriptCheck
[DEBUG] Discovered ruleset with " standard" id.
[DEBUG] Discovered reporter with "checkstyle" id.
[DEBUG] Discovered reporter with "json" id.
[DEBUG] Discovered reporter with "html" id.
[DEBUG] Discovered reporter with "plain" id.
[DEBUG] Initializing "plain" reporter with {verbose=true, color=true, color_name=DARK_GRAY}
[DEBUG] Initializing "plain" reporter with {verbose=true, color=true, color_name=DARK_GRAY}, output=C:\Code\XXXX\build\reports\ktlint\ktlintKotlinScriptCheck\ktlintKotlinScriptCheck.txt
[DEBUG] Initializing "checkstyle" reporter with {verbose=true, color=true, color_name=DARK_GRAY}, output=C:\Code\XXXX\build\reports\ktlint\ktlintKotlinScriptCheck\ktlintKotlinScriptCheck.xml
[DEBUG] Checking C:\Code\XXXX\build.gradle.kts
Resolving .editorconfig files for C:\Code\XXXX\build.gradle.kts file path
[DEBUG] 809ms / 1 file(s) / 0 error(s)

A: To begin there is an error in the configuration of your build.gradle file, in the block Ktlint settings, the line where it appears "version.set (" 9.4.0 ")" is incorrect as well as unnecessary. In any case, if you still decide to use this setting, it should be, for example, version.set ("0.37.2") , since it refers to the Ktlint version and not the jlleitschuh / ktlint-gradle plugin
To solve the problem make the following modifications to the build.gradle.kts file (I use Gradle 6.6.1 with Kotlin DSL in Intellij IDEA community Edition)
Please replace the plugin with the previous version (9.3.0):
build.gradle.kts file in root project
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
import org.jlleitschuh.gradle.ktlint.reporter.ReporterType // for Ktlint reports

plugins {
    kotlin("jvm") version "1.4.10"  // Kotlin Compiler
    id("org.jetbrains.dokka") version "1.4.10" // Documentation Engine For Kotlin
    id("org.jlleitschuh.gradle.ktlint") version "9.3.0" // Kotlin Linter
}

group = "my group" // Replace with your group
version = "1.0-SNAPSHOT"

repositories {
    mavenCentral()
    jcenter()
}

dependencies {
    implementation("org.junit.jupiter:junit-jupiter:5.4.2")
    testImplementation(kotlin("test-junit5"))
    implementation(kotlin("stdlib-jdk8"))
}

tasks.withType<KotlinCompile> {
    kotlinOptions.jvmTarget = "1.8"
}

tasks.test {
    useJUnitPlatform()
}

val compileKotlin: KotlinCompile by tasks
compileKotlin.kotlinOptions {
    jvmTarget = "1.8"
}

val compileTestKotlin: KotlinCompile by tasks
compileTestKotlin.kotlinOptions {
    jvmTarget = "1.8"
}

ktlint {
    // THIS LINE IS NOT necessary and is incorrect -> version.set("9.4.0")
    verbose.set(true)
    outputToConsole.set(true)
    coloredOutput.set(true)
    debug.set(false) // in your configuration this option must be set to true
    android.set(false)
    outputColorName.set("RED")
    ignoreFailures.set(false)
    enableExperimentalRules.set(false)
    reporters {
        reporter(ReporterType.CHECKSTYLE)
        reporter(ReporterType.JSON)
        reporter(ReporterType.HTML)
    }
    filter {
        exclude("**/style-violations.kt")
        exclude("**/generated/**")
        include("**/kotlin/**")
    }
}


text:
Q: Entity Framework 4 - Notification on Associations I am facing a few difficulties with EF 4, foreign keys and INotifyPropertyChanged / the partial methods exposed for scalar properties.
I hope you can help me find the right way to do this.
Image I have a Customer entity with *..1 relationship with the Country entity.
Now, I'd obviously like to be able to do:
var customer = new Customer();
customer.Country = [...]

...but I don't necessarily need the CountryKey property.
I create a Association in EF with the correct cardinality in the .edmx designer. I choose not to "add foreign key properties" in the dialog.
This leaves me with a generated class without the partial OnCountryChanging and OnCountryChanged.
Next, I try to add the foreign key properties, and I now have a OnCountryKeyChanging and OnCountryKeyChanged.
However, the generated code looks like this:
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)]
[DataMemberAttribute()]
public global::System.Int64 CountryKey
{
    get
    {
        return _CountryKey;
    }
    set
    {
        OnCountryKeyChanging(value);
        ReportPropertyChanging("CountryKey");
        _CountryKey = StructuralObject.SetValidValue(value);
        ReportPropertyChanged("CountryKey");
        OnCountryKeyChanged();
    }
}
private global::System.Int64 _CountryKey;
partial void OnCountryKeyChanging(global::System.Int64 value);
partial void OnCountryKeyChanged();

As you can see from the generated code, the PropertyChanged notification occurs with "CountryKey" instead of "Country". This makes data binding in WPF difficult.
My question is: how do I get around this?

*

*Do I wrap my object in a ViewModel, listen to property changes and strip the "Key" part?

*Do I modify the T4 template?

*Or is there a third option I just can't see yet?

I'd greatly appreciate any suggestions here, as I am experimenting with WPF / EF without wrapping each Model property in a ViewModel.

A: The 'best practices' approach is to decorate your model in a viewmodel, exposing the model properties as required. You can create a generic ViewModel with some nifty work with dynamicobject, using perhaps a property mapping etc.
public class DynamicViewModel : DynamicObject, INotifyPropertyChanged, IDisposable
{
    public event PropertyChangedEventHandler PropertyChanged;

    private static readonly Dictionary<Type, Tuple<Dictionary<string, PropertyInfo>, Dictionary<string, string>>> typeDictionary = new Dictionary<Type, Tuple<Dictionary<string, PropertyInfo>, Dictionary<string, string>>>();

    private readonly Dictionary<string, object> additionalProperties = new Dictionary<string, object>();

    private readonly object underlyingObject;
    public object UnderlyingObject
    {
        get
        {
            return underlyingObject;
        }
    }

    private readonly Type type;

    /// <summary>
    /// constructor which takes a model for which it will be extensing its perceived properties
    /// </summary>
    /// <param name="underlyingObject">the underlying object</param>
    public DynamicViewModel(IBindableRfqViewModel underlyingObject) : this(underlyingObject, new Dictionary<string, string>())
    {

    }

    /// <summary>
    /// constructor which takes a model for which it will be extensing its perceived properties as well as a property map
    /// </summary>
    /// <param name="underlyingObject">the underlying object</param>
    /// <param name="propertyMap">a string/string dictionary, where the key is a property on the underlying object, and the value is the name of the dynamic property to be used as a binding target</param>
    public DynamicViewModel(IBindableRfqViewModel underlyingObject, Dictionary<string, string> propertyMap)
    {
        this.underlyingObject = underlyingObject;
        if (underlyingObject is INotifyPropertyChanged)
        {
            ((INotifyPropertyChanged)underlyingObject).PropertyChanged += OnUnderlyingPropertyChanged;
        }

        type = underlyingObject.GetType();
        if (typeDictionary.ContainsKey(type))
        {
            return;
        }
        lock (typeDictionary)
        {
            if (typeDictionary.ContainsKey(type))
            {
                return;
            }
            var forwardPropertyMap = propertyMap;
            var typeProperties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance).ToDictionary(p => p.Name, p => p);
            typeDictionary.Add(type, Tuple.Create(typeProperties,forwardPropertyMap));
        }
    }

    private void OnUnderlyingPropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        this.OnPropertyChanged(e.PropertyName);
    }

    private bool TryGetProperty(string name, out object result)
    {
        try
        {
            var propertyData = typeDictionary[type];
            var modelProperty = name;
            if (propertyData.Item2.ContainsKey(name))
            {
                modelProperty = propertyData.Item2[name];
            }
            if (propertyData.Item1.ContainsKey(modelProperty))
            {
                result = propertyData.Item1[modelProperty].GetValue(underlyingObject, null);
                return true;
            }

            if (additionalProperties.ContainsKey(name))
            {
                result = additionalProperties[name];
                return true;
            }

            result = null;
            return true;
        }
        catch (Exception ex)
        {
            result = null;
            return false;
        }
    }

    /// <summary>
    /// <see cref="DynamicObject.TryGetMember" />
    /// </summary>
    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        return this.TryGetProperty(binder.Name, out result);
    }

    /// <summary>
    /// <see cref="DynamicObject.TryGetIndex" />
    /// </summary>
    public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result)
    {
        return this.TryGetProperty(indexes[0].ToString(), out result);
    }

    private bool TrySetProperty(string name, object value)
    {
        try
        {
            var propertyData = typeDictionary[type];
            var modelProperty = name;
            if (propertyData.Item2.ContainsKey(name))
            {
                modelProperty = propertyData.Item2[name];
            }
            if (propertyData.Item1.ContainsKey(modelProperty))
            {
                propertyData.Item1[modelProperty].SetValue(underlyingObject, value, null);
            }
            else
            {
                if (!additionalProperties.ContainsKey(name))
                {
                    additionalProperties.Add(name, new object());
                }
                additionalProperties[name] = value;
            }

            this.OnPropertyChanged(name);
            return true;
        }
        catch (Exception ex)
        {
            return false;
        }

    }

    /// <summary>
    /// <see cref="DynamicObject.TrySetMember" />
    /// </summary>
    public override bool TrySetMember(SetMemberBinder binder, object value)
    {
        return this.TrySetProperty(binder.Name, value);
    }

    /// <summary>
    /// <see cref="DynamicObject.TrySetIndex" />
    /// </summary>
    public override bool TrySetIndex(SetIndexBinder binder, object[] indexes, object value)
    {
        return indexes.Length == 0 || this.TrySetProperty(indexes[0].ToString(), value);
    }

    private void OnPropertyChanged(string propName)
    {
        var handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propName));
        }
    }

    /// <summary>
    /// IDisposable implementation
    /// </summary>
    public void Dispose()
    {
        if (underlyingObject is INotifyPropertyChanged)
        {
            ((INotifyPropertyChanged)underlyingObject).PropertyChanged -= OnUnderlyingPropertyChanged;
        }
        if (underlyingObject is IDisposable)
        {
            ((IDisposable)underlyingObject).Dispose();
        }
    }
}


text:
Q: java.lang.IllegalArgumentException: Failed to find configured root that contains "insert app directory path here" I am opening the camera to capture a image and i followed this tutorial. Error stated in the title comes when i tried to create different flavor builds configuration for my app.
This is my meta data xml resource file named file_paths for File Provider path configuration -
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="my_images" path="@string/images_file_path"/>
</paths>

I am setting it in manifest as follows -
    <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="@string/authority"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_paths" />
    </provider>

and i am instantiating string resource named "images_file_path" from gradle build file according to build congiguration like this -
productFlavors {
    dev {
        resValue "string", "images_file_path","\"Android/data/com.swinguff.android.dev/files/Pictures\""
    }
    prod {
        resValue "string", "images_file_path","\"Android/data/com.swinguff.android/files/Pictures\""
    }

and i am launching camera in my activity like this -
File photoFile = null;
        try {
            photoFile = createImageFile();
            if (photoFile != null) {
            /*Following line is throwing the error */
            profilePicUri =
            FileProvider.getUriForFile(ApplicationContext.getAppContext(),
                        BuildConfig.AUTHORITY,
                        photoFile);
                launchcamera();
                //Log.d("Musik","camera bug take photo"+photoFile+" "+mPhotoPathForCamera+" "+profilePicUri);
            }
        } catch (Exception ex) {
            // Error occurred while creating the File
            Log.d("CAMERA_BUG","exception "+ex.getMessage()+"\n"+BuildConfig.APPLICATION_ID+"\n"+BuildConfig.AUTHORITY
                +"\n"+getString(R.string.images_file_path));
            Util.showSnackbar(xRoot,getString(R.string.camera__open_error));

        }

private File createImageFile() throws IOException {
    // Create an image file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = "JPEG_" + timeStamp + "_";
    File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
    File image = File.createTempFile(
            imageFileName,  /* prefix */
            ".jpg",         /* suffix */
            storageDir      /* directory */
    );

    // Save a file: path for use with ACTION_VIEW intents
    npath = image.getAbsolutePath();
    return image;
}

Same code does not cause any exception when i set value of path property in above meta data xml resource as a literal string and not by a resouce string value.
I don't understand why this is happening.
Please let me know if i can explain better.Please help and thanks in advance.

A: as Miller pointed out in the comments the solution is to put meta data xml resource file file_paths.xml separately for each build in their corresponding (dev/res/xml or prod/res/xml) folder and set corresponding path value directly in xml file and not by string resource images_file_path

A: <paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_files" path="."/>
</paths>

see this edit your paths like this your problem will solve


text:
Q: Possible to stop availability an in App Store, but keep providing a last update for it? I want to withdraw a lite version of an app, since the full version became free (and features can be bought trough In-App purchase).
But I want to provide an update for the current lite version owners with some message like "Go get the full version for free". But I don't want any newcomers to download the lite version.
What to do now?
Any similar experiences?

A: Maybe you can set App's availability to a future date?


text:
Q: How did time change "by itself"? At the start of act 3, scene 9 the characters have just returned from the past.

 Hermione, Ron and Snape sacrifice themselves to dementors. Scorpius Malfoy runs after Snape's Patronus to the lake. When he rises out of the water time has changed.

What triggered this change? The Time-Turner isn't used in this act as far as I know, only mentioned twice.

A: It would seem that Scorpius used the Time-Turner while underwater
This isn't explicitly mentioned by the stage directions in the script, but they do describe a "bang and a flash" after Scorpius jumps into the lake (emphasis mine):

SCORPIUS thinks and then runs after the doe, and around him the world gets scarier. A bloodcurdling scream goes up at one side. He sees the lake and throws himself inside.
[...]
There is a bang and a flash. And then silence. And then there's more silence.
The Cursed Child Part 2: Act III Scene 9

This is consistent with other uses of the Time-Turner; for example (emphasis mine):

[Hermione] takes the Time-Turner. It begins to vibrate, and then explodes into a storm of movement.
And there is a giant whoosh of light. A smash of noise.
And time stops. And then it turns over, thinks a bit, and begins spooling backwards, slow at first...
There is a bang and a flash and our gang disappear.
The Cursed Child Part 2: Act III Scene 7

It's also worth noting that it was always the plan to do this (emphasis mine):

Hermione: The first task of the tournament took place at the edge of the Forbidden Forest. We turn time here, get to the tournament, block the spell, and then return safely. With precision — it can be done and it won't require us to show our faces outside in our time at all. Then we'll turn time again, make our way to the lake, and reverse the second task.
The Cursed Child Part 2: Act III Scene 7

Ron: We need to use the Time-Turner again — get out of here —
[...]
Hermione: Reversing the next task will change everything.
The Cursed Child Part 2: Act III Scene 9

And the reason for Ron and Hermione's sacrifice is explicitly to give Scorpius more time:

Hermione: Let's keep them here and give the boy the best chance we can.
The Cursed Child Part 2: Act III Scene 9


text:
Q: Why won't google accept my Sitemap.xml? "URL not allowed This url is not allowed for a Sitemap at this location." I have a google custom search pointing at http://xxx/edu_dir_new/* .  I am trying to upload a Sitemap.xml (right now, with just one page)
Sitemap:
<?xml version="1.0" encoding="UTF-8"?>

<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9
http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">
    <url>
        <loc>http://xxx/edu_dir_new/DOEEmployee/i3/JanetRay/Directory.aspx</loc>
    </url>
 </urlset>

The path (edu_dir_new/DOEEmployee/i3/JanetRay/Directory.aspx) is not an actual set of directories, but does serve up a page (by implementing an alternate IHttpModule).
It is unlikely that this site is linked to anywhere else on the web, (because it's in test), but from what I can tell, this shouldn't matter if I specify a sitemap.

A: That error usually means that you have an URL pointing to a different Domain from yours. When you tell google to retrieve the sitemap.xml file, are you using an URL pointing to the same machine? (xxx in your example).
Also, as I guess that you are using Google Webmaster Tools, check that 'xxx' is the name of the server you are configuring. Something silly as omitting the 'www', using the IP address, or simply mistyping a letter could be the cause of the error.
I don't know if google checks it, but if the address actually returns a 3xx http redirect response, it could also refuse the url (if the redirection points to a different domain)


text:
Q: DifferentialEquations.jl multithreading The code below is solving an ODE with different variables, and PAs corresponding to diffrent Δs the only data I'm interested in after each loop. Since the loops are independent I assume I can multithreading the loops so I add Threads.@threads in front of the for loop:
#example
using DifferentialEquations
using Plots;
gr(grid = false, ms = 3, legend = false, msw = 1.5 ,mc = :white)
using Findpeaks

#parameters
P = 1.5
κ = 0.5
Γ = 0.0005

#ODE settings
fs = 400
T = 2*π
y0 = [1, 1]
t0 = [0, 100 *T]
t1 = [0, 50 *T]
function route(dx, x, p, t)
    dx[1] =  1im * (Δ * x[1] - 2 * real(x[2]) * x[1] - 0.5) - κ * x[1]
    dx[2] = -1im * (0.5 * P * abs(x[1])^2 + x[2]) - Γ * x[2]
end
Plots.scatter(1,1) #create new figure

Threads.@threads for i =  -1.3: 0.1 :-0.4
    global Δ = i
    global p =[P, Δ, κ, Γ]
    global prob = ODEProblem(route, collect(Complex{Float64}, y0), t0, p)
    global y1 = solve(prob)
    global y10 = last(y1);#omit unstable parts

    global prob2 = ODEProblem(route, collect(Complex{Float64}, y10), t1, p)
    global y2 = solve(prob2) #calculate steady state data

    global abss = abs.(y2)
    global a = abss[1,:].^2

    global PA = begin
            global peaka = findpeaks(real(a), y2.t)
            global peaka = real(a)[peaka] #peak values
            global pa = Vector{Float64}(undef, length(peaka))
            pa[:] .= Δ #peak locations corresponding to Δ
            pa .+ 1im*peaka
    end
    global fig = scatter!(real(PA), imag(PA))
    display(fig)
end

But it will cause julia terminal to crash(using vscode), seems related to GR.

What is happening?

A: It looks like things thrown from GR. I'm not sure GR is multithreading safe, I would double check that instead of the differential equation solve.


text:
Q: Are there good reasons not to exploit '#!/bin/make -f' at the top of a makefile to give an executable makefile? Mostly for my amusement, I created a makefile in my $HOME/bin directory called rebuild.mk, and made it executable, and the first lines of the file read:
#!/bin/make -f
#
# Comments on what the makefile is for

...

all: ${SCRIPTS} ${LINKS} ...

...

I can now type:
rebuild.mk

and this causes make to execute.
What are the reasons for not exploiting this on a permanent basis, other than this:

*

*The makefile is tied to a single directory, so it really isn't appropriate in my main bin directory.

Has anyone ever seen the trick exploited before?

Collecting some comments, and providing a bit more background information.

*

*Norman Ramsey reports that this technique is used in Debian; that is interesting to know.  Thank you.

*I agree that typing 'make' is more idiomatic.

*However, the scenario (previously unstated) is that my $HOME/bin directory already has a cross-platform main makefile in it that is the primary maintenance tool for the 500+ commands in the directory.

*However, on one particular machine (only), I wanted to add a makefile for building a special set of tools.  So, those tools get a special makefile, which I called rebuild.mk for this question (it has another name on my machine).

*I do get to save typing 'make -f rebuild.mk' by using 'rebuild.mk' instead.

*Fixing the position of the make utility is problematic across platforms.

*The #!/usr/bin/env make -f technique is likely to work, though I believe the official rules of engagement are that the line must be less than 32 characters and may only have one argument to the command.

*@dF comments that the technique might prevent you passing arguments to make.  That is not a problem on my Solaris machine, at any rate.  The three different versions of 'make' I tested (Sun, GNU, mine) all got the extra command line arguments that I type, including options ('-u' on my home-brew version) and targets 'someprogram' and macros CC='cc' WFLAGS=-v (to use a different compiler and cancel the GCC warning flags which the Sun compiler does not understand).

I would not advocate this as a general technique.
As stated, it was mostly for my amusement.  I may keep it for this particular job; it is most unlikely that I'd use it in distributed work.  And if I did, I'd supply and apply a 'fixin' script to fix the pathname of the interpreter; indeed, I did that already on my machine.  That script is a relic from the first edition of the Camel book ('Programming Perl' by Larry Wall).

A: One problem with this for generally distributable Makefiles is that the location of make is not always consistent across platforms. Also, some systems might require an alternate name like gmake.
Of course one can always run the appropriate command manually, but this sort of defeats the whole purpose of making the Makefile executable.

A: I've seen this trick used before in the debian/rules file that is part of every Debian package.

A: To address the problem of make not always being in the same place (on my system for example it's in /usr/bin), you could use
#!/usr/bin/env make -f

if you're on a UNIX-like system.
Another problem is that by using the Makefile this way you cannot override variables, by doing, for example make CFLAGS=....

A: "make" is shorter than "./Makefile", so I don't think you're buying anything.

A: The reason I would not do this is that typing "make" is more idiomatic to building Makefile based projects.  Imagine if every project you built you had to search for the differently named makefile someone created instead of just typing "make && make install".

A: You could use a shell alias for this too.

A: We can look at this another way: is it a good idea to design a language whose interpreter looks for a fixed filename if you don't give it one? What if python looked for Pythonfile in the absence of a script name? ;)
You don't need such a mechanism in order to have a convention based around a known name. Example: Autoconf's ./configure script.


text:
Q: SQL Error [XX000]: ERROR: Spectrum Scan Error: DeltaManifest We have implemented delta lake but one issue as below:
One table can be created and ingested, but after new data has been ingested, we will spectrum scan error:
SQL Error [XX000]: ERROR: Spectrum Scan Error: DeltaManifest
Detail:
error:  Spectrum Scan Error: DeltaManifest
code:      15005
context:   Error fetching Delta Lake manifest [tablenamexxx]/target/_symlink_format_manifest/active_ind=Y/creation_time=2022-05-10/manifest Message: S3ServiceException:The specified key does not exist.,Status 404,Error NoSuchKey,Rid EFHMMKBZ1EG5ZRJV,ExtRid p
query:     4100335
location:  scan_range_manager.cpp:1182
process:   worker_thread [pid=9305]
By further checking, we found it was caused 2 partitions setup for this table. Once the new data ingested, it will expiry the old data, then move all data [creation_time=2022-05-10] to inactive_ind partition.
_symlink_format_manifest has been updated corrrectly, no creation_time=2022-05-10 & active_ind='Y', but partations in Glue Catalog still keep that. That's causing the error.
If we manually run below script to drop the partition, it back to normal. Wondering why and how to resolve it?
ALTER TABLE XXX
DROP PARTITION (creation_time = '2022-05-10', active_ind = 'Y');

A: I had this same error. There weren't any partitions the error referred to in either the _symlink_format_manifest or the partition list. Rerunning the Glue crawler didn't do anything either.
The problem was that there was more than just the one partition and running a query to find the next 'bad' partition was inefficient. To get the full list:
select schemaname, tablename, values, location
from svv_external_partitions
where tablename = 'tablename';

Compare the results to the partitions seen in S3 and delete the list not appearing in S3 using your command:
ALTER TABLE XXX DROP PARTITION (partition_field='2022-10-17')

(dropping the active_ind=Y) command for each.


text:
Q: Помогите с кодом Вроде бы простое задание, но не выходит сделать Коллбэк функция Напишите две функции
letMeSeeYourName(callback) - спрашивает имя пользователя
через prompt и вызывает callback функцию
greet(name) - коллбек принимающий имя и логирующий в консоль строку "Привет <name>"
Реализуй проверку, что prompt не пустой

function greet(name) {
  console.log(`Hi, ${name}`);
}

function letMeSeeYourName(name, callback) {
  let userInput;

  while ((userInput = prompt("What is your name?", ""))) {
    if (userInput === "" || userInput === null) {
      alert("Say your name");
      continue;
    }
  }
  callback(name);
}

letMeSeeYourName(name, greet);

A: В letMeSeeYourName надо передавать только callBack функцию.
В цикле while надо просто проверять переменную userInput.
Для проверки, что userInput пустой, достаточно поставить значение в if, для отрицания используем !

  function greet(name) {
    console.log(`Hi, ${name}`);
  }

  function letMeSeeYourName(callback) {
    let userInput;

    while (!userInput) {
      userInput = prompt("What is your name?", "")
      if (!userInput) {
        alert("Say your name");
      }
    }
    callback(userInput);
  }

  letMeSeeYourName(greet);


text:
Q: Amazon EC2: Public IP changes at reboot Im using Amazon EC2 to host a few websites on a single instance.
From time to time I need to rescale my instance type. This requires a shut-down of the instance, and after relaunch the instance have gotten a new public IP address.
This requires me to change the DNS config (very annoying), which takes up to 12 hours before it works.
Im pretty sure that im doing something wrong here, so my question is: Whats the best approach?

A: An Elastic IP can be assigned to an instance. This is not ephemeral like the Public IP assigned to the instance and thus will be maintained across resizes and can be re-assigned to different instances.
Information on setting this up can be found here: https://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/vpc-ip-addressing.html#vpc-eips


text:
Q: Connect to a FTPS server with mismatched server certificate using Net::FTPTLS I am trying to connect via Net::FTPTLS to a Microsoft-based file server (IIS) which is configured to use FTP on port 22 and requires SSL.
I connect via:
require 'net/ftptls'
ftp = Net::FTPTLS.new()
ftp.connect('host.com', port_number)
ftp.login('Username', 'Password')
ftp.puttextfile('somefile.txt', 'where/to/save/somefile.txt')
ftp.close

Problem is, I get the following error:
hostname does not match the server certificate

It seems that I have to disable the openssl peer verification: OpenSSL::SSL::VERIFY_PEER should become OpenSSL::SSL::VERIFY_NONE.
Any ideas on how to monkey-patch the Net::FTPTLS class? Has anyone done this successfully?

A: Instead using Net::FTPTLS, use Ruby 2.4+ with the following code:
require 'net/ftp'
ftp = Net::FTP.new(nil, ssl: {:verify_mode => OpenSSL::SSL::VERIFY_NONE})
ftp.connect('host.com', port_number)
ftp.login('Username', 'Password')
ftp.puttextfile('somefile.txt', 'where/to/save/somefile.txt')
ftp.close

A: What I did, rather than monkeypatching ruby itself, was bring a copy of this into /lib of my project.
module Net

  class FTPTLS < FTP
    def connect(host, port=FTP_PORT)
      @hostname = host
      super
    end

    def login(user = "anonymous", params = {:password => nil, :acct => nil, :ignore_cert => false})
      store = OpenSSL::X509::Store.new
      store.set_default_paths
      ctx = OpenSSL::SSL::SSLContext.new('SSLv23')
      ctx.cert_store = store
      ctx.verify_mode = params[:ignore_cert] ? OpenSSL::SSL::VERIFY_NONE : OpenSSL::SSL::VERIFY_PEER
      ctx.key = nil
      ctx.cert = nil
      voidcmd("AUTH TLS")
      @sock = OpenSSL::SSL::SSLSocket.new(@sock, ctx)
      @sock.connect
      @sock.post_connection_check(@hostname) unless params[:ignore_cert]
      super(user, params[:password], params[:acct])
      voidcmd("PBSZ 0")
    end
  end
end

I also cleaned up the param passing a bit. You would use this like so:
  require 'ftptls'  # Use my local version, not net/ftptls
  @ftp_connection = Net::FTPTLS.new()
  @ftp_connection.passive = true
  @ftp_connection.connect(host, 21)
  @ftp_connection.login('user', :password => 'pass', :ignore_cert => true)

HTH

A: This works fine for me. #ROR
ftp = Net::FTP.new("ftps.host.com", ftp_options)

open("where/is/your/file/somefile.txt") do |file_data|
  ftp.putbinaryfile(file_data, 'where/to/save/somefile.txt')
end

ftp.puttextfile('somefile.txt', 'where/to/save/somefile.txt')

def ftp_options
  {
    port: FTP_PORT,
    username: 'ftp_user',
    password: 'password',
    passive:  true,
    ssl: { verify_mode: 0 }
  }
end

Remember that you have to provide ftps.hostname.com.


text:
Q: R could not find function "col2rgb" When I started R it came with the following Error

Error in alpha(fill, alpha) : could not find function "col2rgb"

when I try to compile PDF in knitr I get the same error:

Error in alpha(fill, alpha) : could not find function "col2rgb"
Calls: .First ... grob -> gpar -> validGP -> numnotnull -> match -> alpha
Execution halted

I don't know how to isolate this problem, since it last I used R and no when I start it produces the error. From what I can gather the col2rgb should be in the base package {grDevices}
library(grDevices)
grDevices::col2rgb("white")
  [,1]
red    255
green  255
blue   255

Which seems to work fine.
The error is independent of knitr
Anyone know a fix, or can give any suggestion as to how to isolate the problem?
Best Regards

A: You must have saved your workspace.  Almost all experienced R users never do this.... so don't do that in the future.
For now, you'd find an .Rdata or .RData or similar in your working directory/folder and rename it (so if it contains important stuff you can still load(.) it manually afterward.
After that, starting R should not give your message anymore
(the grDevices package is one of the packages that are always loaded in R ((unless you specifically disable that; which may even be difficult in RStudio))).

A: Found it!
It was due to a source("") of some often used functions that was sourced at startup via the .Rprofile. when i moved the sourcing to after Rstudio had fully started it works - even knitr.


text:
Q: Automatically retrieve evaluation spot row number Suppose I need to define a matrix of the form
{{a, b, Reduce[a<b]}, {c, d, Reduce[c<d]}, {e, f, Reduce[e<f]}}

but with a lot more rows and automating the Reduce argument by making it be "first element of this row < second element of this row".
How would I do that? I understand the question doesn't make much sense in a coding grammar or optimization way, but I would like to learn how to evaluate "this row" in this sense.

A: Assuming you have the matrix with the last column missing, you can Map or Apply over the individual rows of the matrix & add some new columns. Here are two possible approaches:
{##, Reduce[Less@##]} & @@@ {{a, b}, {c, d}, {e, f}}
(* {{a, b, b ∈ Reals && a < b}, {c, d, d ∈ Reals && c < d}, {e, f, f ∈ Reals && e < f}} *)
Append[#, Reduce[Less @@ #]] & /@ {{a, b}, {c, d}, {e, f}}
(* same output *)


text:
Q: How to find the last occurrence of a certain observation in grouped data in R? I have data that is grouped using dplyr in R. I would like to find the last occurrence of observations ('B') equal to or greater than 1 (1, 2, 3 or 4) in each group ('A'), in terms of the 'day' they occurred. I would like the value of 'day' for each group to be given in a new column.
For example, given the following sample of data, grouped by A (this has been simplified, my data is actually grouped by 3 variables):
A  B  day
a  2  1
a  2  2
a  1  5
a  0  8
b  3  1
b  3  4
b  3  6
b  0  7
b  0  9
c  1  2
c  1  3
c  1  4

I would like to achieve the following:
A  B  day last
a  2  1   5
a  2  2   5
a  1  5   5
a  0  8   5
b  3  1   6
b  3  4   6
b  3  6   6
b  0  7   6
b  0  9   6
c  1  2   4
c  1  3   4
c  1  4   4

I hope this makes sense, thank you all very much for your help! I have thoroughly searched for my answer online but couldn't find anything. However, if I have accidentally duplicated a question then I apologise.

A: We can try
library(data.table)
setDT(df1)[, last := day[tail(which(B>=1),1)] , A]
df1
#    A B day last
# 1: a 2   1    5
# 2: a 2   2    5
# 3: a 1   5    5
# 4: a 0   8    5
# 5: b 3   1    6
# 6: b 3   4    6
# 7: b 3   6    6
# 8: b 0   7    6
# 9: b 0   9    6
#10: c 1   2    4
#11: c 1   3    4
#12: c 1   4    4

Or using dplyr
library(dplyr)
df1 %>%
   group_by(A) %>%
   mutate(last = day[max(which(B>=1))])

Or use the last function from dplyr (as @docendo discimus suggested)
df1 %>%
   group_by(A) %>%
   mutate(last= last(day[B>=1]))

For the second question,
setDT(df1)[, dayafter:= if(all(!!B)) NA_integer_  else
             day[max(which(B!=0))+1L] , A]
#    A B day dayafter
# 1: a 2   1        8
# 2: a 2   2        8
# 3: a 1   5        8
# 4: a 0   8        8
# 5: b 3   1        7
# 6: b 3   4        7
# 7: b 3   6        7
# 8: b 0   7        7
# 9: b 0   9        7
#10: c 1   2       NA
#11: c 1   3       NA
#12: c 1   4       NA

A: Here is a solution that does not require loading external packages:
df <- structure(list(A = structure(c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L,
2L, 3L, 3L, 3L), .Label = c("a", "b", "c"), class = "factor"),
B = c(2L, 2L, 1L, 0L, 3L, 3L, 3L, 0L, 0L, 1L, 1L, 1L), day = c(1L,
2L, 5L, 8L, 1L, 4L, 6L, 7L, 9L, 2L, 3L, 4L)), .Names = c("A",
"B", "day"), class = "data.frame", row.names = c(NA, -12L))

x <- split(df, df$A, drop = TRUE)

tp <- lapply(x, function(k) {
  tmp <- k[k$B >0,]
  k$last <- tmp$day[length(tmp$day)]
  k
})

do.call(rbind, tp)

         A B day last
#a.1  a 2   1    5
#a.2  a 2   2    5
#a.3  a 1   5    5
#a.4  a 0   8    5
#b.5  b 3   1    6
#b.6  b 3   4    6
#b.7  b 3   6    6
#b.8  b 0   7    6
#b.9  b 0   9    6
#c.10 c 1   2    4
#c.11 c 1   3    4
#c.12 c 1   4    4


text:
Q: Getting error: Undefined offset: 1 Its look like everything ok. It shows the result as well but it also shows Undefined offset: 1 error. Please help me with this.

$url = "http://www.test.com";
$pageContent = file_get_contents($url);
$stepA = explode("</title>",$pageContent);
$stepB = explode("<title>",$stepA[0]);
$stepC = $stepB[1];
if($stepC == "Not Found"){
    echo $stepC = "NA";
} else{
    echo $stepC = "ok";
}

A: Add some code like bellow:
$url = "http://www.test.com";
$pageContent = file_get_contents($url);

$stepA = explode("</title>",$pageContent);

if(isset($stepA)) {
    $stepB = explode("<title>",$stepA[0]);

    $stepC = isset($stepB) ? $stepB[1] : null;

    if($stepC == "Not Found"){
        echo $stepC = "NA";
    } else{
        echo $stepC = "ok";
    }
}

A: I think you have to use preg_match_all with regex simply you code
http://php.net/manual/fr/function.preg-match-all.php
$url = "http://www.test.com";
$pageContent = file_get_contents($url);

preg_match_all("#<title>(.*)<\/title>#sU",$pageContent, $matches);

 if(isset($matches[0][1]) && $matches[0][1] == "Not Found")
        $stepC = "NA";
 } else{
        $stepC = "ok";
 }
 echo $stepC;


text:
Q: CPLEX/OPL three-dimensional decision variable Is it possible to use three-dimensional decision variable in OPL?
I want to do optimization on the network graph. In particular, I need two-dimensional decision variable for each pair of nodes. I can avoid that with single three-dimensional decision variable.

A: of course.
You can see and example in CPLEX_Studio127\opl\examples\opl\models\NoughtsAndCrosses
Three-dimensional Noughts and Crosses
Problem 17 from Model Building in Mathematical Programming by H.P. Williams.
>    range r=1..3;
>    dvar boolean cell[r][r][r];


text:
Q: SQLCipher "sqlite3_key" encrypted database can't be opened using SqliteManger tool here is my code to create a new encrypted database
sqlite3 *db;

if (sqlite3_open([databasePath UTF8String], &db) == SQLITE_OK) {
    const char* key = "sssri";    //the key to encrypt the database
    sqlite3_key(db, key, strlen(key));    //using the SQLCipher to encrypt database
    if (sqlite3_exec(db, (const char*) "SELECT count(*) FROM sqlite_master;", NULL, NULL, NULL) == SQLITE_OK) {
        NSLog(@"password is correct, or, database has been initialized");  //this step is also successful
        if(sqlite3_exec(db, (const char*)"create Table student (name char(4) primary key,class varchar(50) not null)", NULL, NULL, NULL)== SQLITE_OK)
        {
            NSLog(@"create a table")    //create a table if not the database is empty,and create successfully
            ;            }

    } else {
        NSLog(@"incorrect password!");
  }

    sqlite3_close(db);

but when i try to open the sqlite database in my app documents using the SqliteManger tool ,i input the "sssri" key ,the database can't be opened correctly.
Why?Some help will be appreciated!

A: The SQLite Manager tool does not support SQLCipher.  If you would like to interact with a SQLCipher database, outside of your codebase, consider using the SQLCipher command line shell.

A: Try using version 4.3.0 (or later): http://www.sqlabs.com/news/sqlitemanager/


text:
Q: Verificar Webhooks openpay(paypal) -PHP tengo que verificar un webhooks que yo creé y esto me dice openpay:
Al terminar la configuración de registro, Openpay enviará mediante POST un mensaje JSON a la URL indicada, conteniendo un objeto de notificación Webhook. Tu servicio deberá guardar el código de verificación de alguna manera, y regresar el estado 200 OK.
Como puedo obtener el codigo de verificacion en la url que ingrese ?
este es el json que me mandara OpenPay:
{
    "type" : "verification",
    "event_date" : "2013-11-22T11:04:49-06:00",
    "verification_code" : "UY1qqrxw"
}

A: $tuResultado = json_decode('Nombre de la variable que recibe el POST');

$verification = $tuResultado->verification_code;

Con esto obtienes el codigo de verificación que manda OpenPay.


text:
Q: Why is the first condition of "else if" statement always false? I am assuming this is some logic error I am overlooking and am hoping someone can enlighten me on the mechanics of Java in this scenario. The first condition in the if else statements (id == R.id.checkbox1) are highlighted by Android Studio as being always false, why?
@Override
public void onClick(View view) {

    int id = view.getId();
    int page = viewPager.getCurrentItem();
    boolean cBoxChecked = false;

    switch(page) {
        case 0: case 1: case 3: case 4: case 6: case 10:
            if(id == R.id.button2)
                answersStatus.set(page, true);
            else
                answersStatus.set(page, false);
        case 2:
            if(id == R.id.button1)
                answersStatus.set(page, true);
            else
                answersStatus.set(page, false);
        case 5: case 7:
            if(id == R.id.checkbox1 || id == R.id.checkbox4 && cBoxChecked)
                cBoxChecked = true;
                  //____________________
            else if(id == R.id.checkbox1 || id == R.id.checkbox4 && !cBoxChecked)
                  //^^^^^^^^^^^^^^^^^^^^
                answersStatus.set(page, true);
            else
                answersStatus.set(page, false);
        case 8:
            if(id == R.id.checkbox1 || id == R.id.checkbox5 && cBoxChecked)
                cBoxChecked = true;
                  //____________________
            else if(id == R.id.checkbox1 || id == R.id.checkbox5 && !cBoxChecked)
                  //^^^^^^^^^^^^^^^^^^^^
                answersStatus.set(page, true);
            else
                answersStatus.set(page, false);
        case 9:

    }
}

A: Here's one of the code snippets.
if(id == R.id.checkbox1 || id == R.id.checkbox4 && cBoxChecked)
    cBoxChecked = true;
else if(id == R.id.checkbox1 || id == R.id.checkbox4 && !cBoxChecked)
    answersStatus.set(page, true);
else
    answersStatus.set(page, false);

The "then" statement of the first if will be executed when EITHER id == R.id.checkbox1 is true OR when id == R.id.checkbox4 && cBoxChecked is true.
So if you get to the else if, that means that id == R.id.checkbox1 CANNOT BE true.  That is what the compiler is saying.
In Java (and in most / all other programming languages I have encountered) precedence of && is higher than ||.
Maybe you meant to write this:
if ((id == R.id.checkbox1 || id == R.id.checkbox4) && cBoxChecked)
    cBoxChecked = true;
else if ((id == R.id.checkbox1 || id == R.id.checkbox4) && !cBoxChecked)
    answersStatus.set(page, true);
else
    answersStatus.set(page, false);

A: && has more priority then ||
So when you are writing below statement:
if(id == R.id.checkbox1 || id == R.id.checkbox4 && cBoxChecked)

It will check either for
id == R.id.checkbox1

or
id == R.id.checkbox4 && cBoxChecked

Now the other else if statement says:
else if(id == R.id.checkbox1 || id == R.id.checkbox4 && !cBoxChecked)

which will again be split into
id == R.id.checkbox1

or
id == R.id.checkbox4 && !cBoxChecked

As the first statement "id == R.id.checkbox1" is same and whenever it will be true, the statements inside if will be called instead of else if.
Hope that makes sense.


text:
Q: How do I achieve this simple boxes layout I'm trying to create the following layout using only regular CSS display properties (block, inline..) not using flex or grid.

The top thing(bandeau) should have a height of 100px and horizontal margins that are 50px.
Both the left and right columns should have a width of 100px.
The footer thingy(pied) should have a height of 80px and horizontal margins of 75px.

body {
  margin: 0;
  padding: 0;
  background: black;
  min-height: 100%;
}

.bandeau {
  height: 100px;
  background: white;
  margin: 0 50px;
}

.menuGauche {
  width: 50px;
  background: lightblue;
  height: calc(100% - 80px);
  margin: 0 0 80px 0;
  position: absolute;
}

.ecran {
  background: lightgreen;
  width: calc(100% - 100px);
  height: calc(100% - 80px);
  position: absolute;
  margin: 0 50px;
}

.menuDroite {
  width: 50px;
  background: lightblue;
  height: calc(100% - 80px);
  margin: 0 0 80px 0;
  position: absolute;
  left: calc(100% - 50px);
}

.pied {
  height: 80px;
  background: white;
  margin: 0 75px;
  width: 100%;
  position: absolute;
  bottom: 0;
}

A: As a beginner, you should avoid using absolute positionning and learn  display , then float.
Nowdays display flex makes it easier.
You may also use tags which can be meaningfull for the contents they hold.
Here an example via flex:

html {
  height: 100%;
}
body {
  margin: 0;
  padding: 0;
  background: black;
  min-height: 100%;
  display: flex;
  flex-direction: column;
}
main {
  flex: 1;
  display: flex;
}
.bandeau {
  height: 100px;
  background: white;
  margin: 0 50px;
}

.menuGauche {
  width: 50px;
  background: lightblue;
}

.ecran {
  background: lightgreen;
  flex: 1;
}

.menuDroite {
  width: 50px;
  background: lightblue;
}

.pied {
  height: 80px;
  background: white;
  margin: 0 75px;
}

Play the snippet full page or play with:https://codepen.io/anon/pen/rJMrgz.

Here is a tutorial (among others) to start with : https://css-tricks.com/snippets/css/a-guide-to-flexbox/
( 101 advises : for french readers  https://www.alsacreations.com/article/lire/53-guide-de-survie-du-positionnement-css.html )

A: When I am doing this kind of layout, I try to group them horizontally, so the two columns will  be wrapped in another div. similar to this:
<!DOCTYPE html>

I've used float and assume a height for the middle section as it was not specified. Here is a plunk. Hope this helps!

A: You can use the display:table on some elements to achieve the result. so wrap your main content then display it as table.

html,
body {
  height: 100%;
}
body{
margin: 0;
padding: 0;
background: black;
}

.bandeau{
    height: 100px;
    background: white;
    margin: 0 50px;
}
.content-wrapper {
    display: table;
    height: calc(100% - 180px);
    width: 100%;
}
.content-wrapper > div{
  display:table-cell;
}

.menuGauche,
.menuDroite{
    width: 100px;
    background: lightblue;
}

.ecran{
    background: lightgreen;
}

.pied{
    height: 80px;
    background: white;
    margin: 0 75px;
}


text:
Q: Restar a fecha actual un numero de dias y obtener ña fecha despues de la resta c# Alguien sabe si hay una función en c# que me permita obtener el la fecha final al restar un entero es decir:
seria algo así:
FechaActual = datatime.Now
int numeroDias = 10;

dataTime.Now - numeroDias = Fecha calculado desde resta

Alguien sabe si hay alguna función para hacerlo. Les agradezco su ayuda.

A: Tienes el método de DateTime AddDays() que te permite sumar (o restar si pones un entero en negativo) días a una fecha.
int NumeroDias = 12;
DateTime Hoy = DateTime.Now;
DateTime FechaRestada = Hoy.AddDays(-NumeroDias);


text:
Q: string.match is too broad, is there any other alternatives that would work better? Currently I am getting passed a bunch of strings from a home automation controller to our driver which I am currently developing.
I receive messages such as ZAA and other code which may be AA but the string.match sometimes will match the AA with the ZAA if statement.
This issue is much more wide spread than just those two strings (probably around to 10-15 other similarities).
I understand that I could add more conditions to the if/elseif statements but surely there is an exact match version?
Any ideas would be greatly appreciated.
Example; Even though the string is "AA" it will match "ZAA"
stringInput = "AA"

if string.match("ZAA", stringInput) then
    print("I matched: ZAA")
elseif string.match("AA", stringInput) then
    print("I matched: AA")
end

A: If you want an exact match, just use ==.
if stringInput == 'ZAA' then
    print('I matched: ZAA')
elseif stringInput == 'AA' then
    print('I matched: AA')
end

A: From the Lua 5.3. Reference Manual: string.match

string.match (s, pattern [, init])
Looks for the first match of pattern (see §6.4.1) in the string s. If it finds one, then match
returns the captures from the pattern; otherwise it returns nil. If
pattern specifies no captures, then the whole match is returned. A
third, optional numeric argument init specifies where to start the
search; its default value is 1 and can be negative.

so
local inputString = "AA"
string.match("ZAA", inputString)

will match because "AA" is in "ZAA".
You confused the function arguments s and pattern.
local inputString = "AA"
inputString:match("ZAA")
will not match because the pattern contains more characters than inputString.
But as
local inputString = "ZAA"

will both match
inputString:match("AA") and inputString:match("ZAA") you'll probably have to add more constraints.
Please read the manual!


text:
Q: Angular2 Material errors in webpack when importing MaterialModule I am following the steps from the getting started page
https://github.com/angular/material2/blob/master/GETTING_STARTED.md
So far I have installed material with the following
npm install --save @angular/material

Now I am attempting to import the MaterialModule into my app component
import { MaterialModule } from '@angular/material';

Which causes webpack to throw a ton of errors like
ERROR in [default] C:/mypathSource/Repos/dir/Web.Angular/node_modules/@angular/material/menu/menu-item.d.ts:14:27
';' expected.
ERROR in [default] C:/mypathSource/Repos/dir/Web.Angular/node_modules/@angular/material/menu/menu-item.d.ts:14:29
Duplicate identifier 'string'.
ERROR in [default] C:/mypathSource/Repos/dir/Web.Angular/node_modules/@angular/material/menu/menu-item.d.ts:15:4
Duplicate identifier 'readonly'.
ERROR in [default] C:/mypathSource/Repos/dir/Web.Angular/node_modules/@angular/material/menu/menu-item.d.ts:15:13
'=' expected.
ERROR in [default] C:/mypathSource/Repos/dir/Web.Angular/node_modules/@angular/material/menu/menu-item.d.ts:15:13
Cannot find name '_tabindex'.
ERROR in [default] C:/mypathSource/Repos/dir/Web.Angular/node_modules/@angular/material/menu/menu-item.d.ts:15:22
';' expected.
ERROR in [default] C:/mypathSource/Repos/dir/Web.Angular/node_modules/@angular/material/menu/menu-item.d.ts:15:24
Duplicate identifier 'string'.
ERROR in [default] C:/mypathSource/Repos/dir/Web.Angular/node_modules/@angular/material/menu/menu-trigger.d.ts:26:4
Duplicate identifier 'readonly'.
ERROR in [default] C:/mypathSource/Repos/dir/Web.Angular/node_modules/@angular/material/menu/menu-trigger.d.ts:26:13
'=' expected.
ERROR in [default] C:/mypathSource/Repos/dir/Web.Angular/node_modules/@angular/material/menu/menu-trigger.d.ts:26:13
Cannot find name 'menuOpen'.
ERROR in [default] C:/mypathSource/Repos/dir/Web.Angular/node_modules/@angular/material/menu/menu-trigger.d.ts:26:21
';' expected.

what am I doing wrong?

A: After importing the MaterialModule from the angular/material library, you'll need to add that import to the NgModule like so:
(in the same ts file you have imported the MaterialModule):
@NgModule({
  imports: [
    ...
    MaterialModule.forRoot(),
    ...
  ]
  ...
})

That will add that Module so you can use it in your app.

A: I ended up updating all the versions of my node modules by coping the package.json from the angular/webpack starter kit and the errors went away.


text:
Q: Raku operator for 2's complement arithmetic? I sometimes use this:
$ perl -e "printf \"%d\", ((~18446744073709551592)+1)"
24

I can't seem to do it with Raku. The best I could get is:
$ raku -e "say +^18446744073709551592"
-18446744073709551593

So: how can I make Raku give me the same answer as Perl ?

A: Gotta go with (my variant¹ of) Liz's custom op (in her comment below).
sub prefix:<²^>(uint $a) { (+^ $a) + 1 }

say ²^ 18446744073709551592; # 24

My original "semi-educated wild guess"² that turned out to be acceptable to @zentrunix and the basis for Liz's op:
say (+^ my uint $ = 18446744073709551592) + 1; # 24

\o/ It works!³
Footnotes
¹ I flipped the two character op because I wanted to follow the +^ form, have it sub-vocalize as "two's complement", and avoid it looking like ^2.
² One line of thinking was about the particular integer. I saw that 18446744073709551592 is close to 2**64. Another was that integers are limited precision in Perl unless you do something to make them otherwise, whereas in Raku they are arbitrary precision unless you do something to make them otherwise. A third line of thinking came from reading the doc for prefix +^ which says "converts the number to binary using as many bytes as needed" which I interpreted as meaning that the representation is somehow important. Hmm. What if I try an int variable? Overflow. (Of course.) uint? Bingo.
³ I've no idea if this solution is right for the wrong reasons. Or even worse. One thing that's concerning is that uint in Raku is defined to correspond to the largest native unsigned integer size supported by the Raku compiler used to compile the Raku code. (Iirc.) In practice today this means Rakudo and whatever underlying platform is being targeted, and I think that almost certainly means C's uint64_t in almost all cases. I imagine perl has some similar platform dependent definition. So my solution, if it is a reasonable one, is presumably only portable to the degree that the Raku compiler (which in practice today means Rakudo) agrees with the perl binary (which in practice today means P5P's perl) when run on some platform. See also @p6steve's comment below.

A: 'Long-hand' answer:
raku -e 'put ( (18446744073709551592.base(2) - 0b1).comb.map({!$_.Int+0}).join.parse-base(2));'

OR
raku -e 'say 18446744073709551592.base(2).comb.map({!$_.Int+0}).join.parse-base(2) + 1;'

Sample Output: 24
The answers above (should?) implement "Two's-Complement" encoding directly. Neither uses Raku's +^ twos-complement operator. The first one subtracts one from the binary representation, then inverts. The second one inverts first, then adds one. Neither answer feels truly correct, yet the same answer as Perl5 is obtained (24).
Looking at the Raku Docs page, one would conclude that the "twos-complement" of a positive number would be negative, hence it's not clear what the Perl (and now Raku) answers represent. Hopefully the foregoing is somewhat useful.
https://docs.raku.org/routine/+$CIRCUMFLEX_ACCENT


text:
Q: jQuery dropdown selected option show input field jQuery get value problem.
How do I get the input field when option value other is selected?
 <script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
 <script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>

 <select  id="carm3" name="interest">
 <option value="">    Dogs</option>
 <option value="">    Cats</option>
 <option value="">    Rabbits</option>
  <option  value="    other">other</option>
  </select>
 <input type="text" name="other_interest" style="display:none" />

<script>
      jQuery(document).ready(function() {
          jQuery("#carm3").val(3).text(function() {
          if (jQuery.inArray(jQuery("other"))){
           jQuery('input[name=other_interest]').show();
              return false;
          }
        });

  });

A: Here you are: http://jsfiddle.net/Lxen6qp1/

jQuery(document).ready(function() {
    jQuery("#carm3").change(function() {
        if (jQuery(this).val() === 'other'){
            jQuery('input[name=other_interest]').show();
        } else {
            jQuery('input[name=other_interest]').hide();
        }
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="carm3" name="interest">
    <option value="d">Dogs</option>
    <option value="c">Cats</option>
    <option value="r">Rabbits</option>
    <option value="other">other</option>
</select>
<input type="text" name="other_interest" style="display:none" />

A: Like this - please note I removed the leading spaces in the value and handle a reload.

$(function() {
  $("#carm3").on("change",function() {
    $('input[name="other_interest"]').toggle(this.value == "other");
  }).change(); // in case of reload
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="carm3" name="interest">
  <option value="">Dogs</option>
  <option value="">Cats</option>
  <option value="">Rabbits</option>
  <option value="other">other</option>
</select>
<input type="text" name="other_interest" style="display:none" />


text:
Q: How do I use Intent to go to one of five (user selected via tab) activities? On my main activity I have a tab with 5 choices. I am trying to write in persistence using SharedPreferences to allow the user to select one of the tabs (as well as set a timer), and then those selections are saved so that one of five activities will come up when the "Start" button is pushed. I am trying to write this functionality into an Intent in the onClickListener for the "Start" button, so that it will use the currently selected tab and go to the the activity that goes with that tab. The 5 tabs, all have their own themed activity that they will go to (not by clicking the tab, but rather the "Start" button), so what should my Intent code show in order for this to happen?
I was thinking, the choice of activity should go into the 2nd parameter of the new Intent() part of the code, since that determines which class it goes to (for now I have a "dummy" activity in there, but it should be changed). But since it must be based on what the user selected (whichever tab is currently selected), it should somehow say that, but how? Or is the answer to write an implicit Intent (which, from my limited understanding, allows an Intent to choose from multiple factors in determining the best activity to go to)?
I am not writing in the value to be saved (and passed on) for the timer set up yet, so we just need to focus on the tab selection being saved and passed through an Intent for now. Thanks for your help.
P.S. I'm not quite sure my SharedPreferences code is correct, so suggest changes if you think something is wrong.
NOTE: PLEASE, PLEASE let me know if this question is unclear. This is the 2nd time I've asked it (simplified from the last time) and I'm so far not getting a response. I just really need to know how to go from one tab choice through the Intent to the activity associated with that tab choice (so, one of five choices). How can an Intent allow room for this choice? I MUST use SharedPreferences for other reasons (the timer) but really, this posting is about how to properly write an Intent, so don't get too hung up on the SharedPreferences part. If anyone can attempt an answer, I would be so very, very grateful, thanks you in advance!!
MainSelectorActivity.java
package com.azurespot.disastertimer.app;

import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTabHost;
import android.view.View;
import android.widget.Button;

import com.azurespot.disastertimer.app.tabs.GodzillaTab;
import com.azurespot.disastertimer.app.tabs.NuclearTab;
import com.azurespot.disastertimer.app.tabs.TsunamiTab;
import com.azurespot.disastertimer.app.tabs.VolcanoTab;
import com.azurespot.disastertimer.app.tabs.ZombieTab;

public class MainSelectorActivity extends FragmentActivity {

    Resources resrc;
    FragmentTabHost tabHost;
    private Button btnStart;
    public static final String TABTIMER = "Tab_and_Timer";

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

        tabSetUp();

        btnStart = (Button) findViewById(R.id.btnStart);
        btnStart.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent i = new Intent(getApplicationContext(),
                        MediaActivity.class);
                startActivity(i);
            }
        });

        tabAndTimerPersist();

    }

    public void tabSetUp() {
        resrc = getResources();

        // TabHost setup & functionality
        tabHost = (android.support.v4.app.FragmentTabHost)findViewById(android.R.id.tabhost);
        tabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);

        //------Zombie tab------
        //Creates tab and sets zombie image in view
        tabHost.addTab(tabHost.newTabSpec("zombie").setIndicator("",
                        getResources().getDrawable(R.drawable.ic_tab_zombie_selected)),
                ZombieTab.class, null);

        //------Nuclear tab------
        //Creates tab and sets nuclear image in view
        tabHost.addTab(tabHost.newTabSpec("nuclear").setIndicator("",
                        getResources().getDrawable(R.drawable.ic_tab_nuclear_selected)),
                NuclearTab.class, null);

        //------Tsunami tab------
        //Creates tab and sets tsunami image in view
        tabHost.addTab(tabHost.newTabSpec("tsunami").setIndicator("",
                        getResources().getDrawable(R.drawable.ic_tab_tsunami_selected)),
                TsunamiTab.class, null);

        //------Godzilla tab------
        //Creates tab and sets tsunami image in view
        tabHost.addTab(tabHost.newTabSpec("godzilla").setIndicator("",
                        getResources().getDrawable(R.drawable.ic_tab_godzilla_selected)),
                GodzillaTab.class, null);

        //------Volcano tab------
        //Creates tab and sets volcano image in view
        tabHost.addTab(tabHost.newTabSpec("volcano").setIndicator("",
                        getResources().getDrawable(R.drawable.ic_tab_volcano_selected)),
                VolcanoTab.class, null);

        //set Zombie tab as default (zero based)
        tabHost.setCurrentTab(0);
    }

    @Override
    protected void onPause() {
        super.onPause();
        tabAndTimerPersist();
    }

    private void tabAndTimerPersist() {

        SharedPreferences prefs = getSharedPreferences(TABTIMER, MODE_PRIVATE);

        tabHost.getCurrentTab();

        SharedPreferences.Editor editor = prefs.edit();
        editor.putInt("zombie", 0);
        editor.putInt("nuclear", 0);
        editor.putInt("tsunami", 0);
        editor.putInt("godzilla", 0);
        editor.putInt("volcano", 0);
        editor.commit();
    }
}

A: TabHost tabHost;
Intent intent;
TabHost.TabSpec spec;
Resources res;
            spec = tabHost.newTabSpec("A")
            .setIndicator(getTabView("A","#333333"))
            .setContent(new Intent().setClass(this,A.class));
    tabHost.addTab(spec);

    spec = tabHost
            .newTabSpec("B")
            .setIndicator(getTabView("B","#ffffff"))
            .setContent(new Intent().setClass(this,B.class));
    tabHost.addTab(spec);
        tabHost.setCurrentTab(1);
        setTabColor(tabHost);

//Your on tab change listener call setTabColor(tabHost);
private View getTabView(String text, String color)
{
    LayoutInflater inf_manifesto=getLayoutInflater();
    View v=inf_manifesto.inflate(R.layout.customt_tab, null);
        TextView t = (TextView)v.findViewById(R.id.txt);
    t.setText(text);
    t.setTextColor(Color.parseColor(color));

    return v;
}
   public static void setTabColor(TabHost tabhost)
{
    for(int i=0;i<tabhost.getTabWidget().getChildCount();i++)
    {

 tabhost.getTabWidget().getChildAt(i).setBackgroundColor(Color.parseColor("#3d99d1"));
        TextView tv1 = (TextView)tabhost.getTabWidget().getChildAt(i).findViewById(R.id.txt);
        tv1.setTextColor(Color.parseColor("#ffffff"));

    }
    tabhost.getTabWidget().getChildAt(tabhost.getCurrentTab()).setBackgroundColor(Color.parseColor("#ffffff")); // selected
    TextView tv2 = (TextView)tabhost.getTabWidget().getChildAt(tabhost.getCurrentTab()).findViewById(R.id.txt);
    tv2.setTextColor(Color.parseColor("#333333"));

}

Use this way to create tabs.


text:
Q: Matlab Fmincon : Setting Constraints with dependency This may be really simple question for MATLAB fmincon users:
I have a function Y = AX, where A is a vector 1 x N of constants, Y is a scalar constant, and X is a vector N x 1; I need to find the optimal values of X such that
Y - A*X = 0. Initial values for X come from a N x 1 vector X0. Also
X0(1) < X0(2) < ... X0(N)

The constraints are:
0 <= X(1);
X(1) < X(2);
X(2) < X(3);
...
...
X(N-1) < X(N);
X(N) <= 1;

and
X0(1) <= X(1);
X0(2) <= X(2);
X0(3) <= X(3);
...
...
X0(N-1) <= X(N-1);

My attempt at this problem was:
[X, fval] = fmincon(@(X)Y - A*X, X0,[],[],[],[],X0,[X(2:end);1],[],options);

I don't think the results I get are correct with this method.
Another attempt was this:
[X, fval] = fmincon(@(X)Y - A*X, X0,AA,zeros(N-1,1),[],[],[],[],[],options);

where
AA = [1 -1 0 0 0 ... N;
      0 1 -1 0 0 ... N;
      .
      .
      0 0 0 0 0 ... 1 -1];  (N-1 Rows)

with failure as well.
Any suggestions, hints would be very welcome! I hope I have given enough information regarding the problem.
Following Shai's suggestion I have tried this :
[X, fval] = fmincon(@(X) abs(Y - A*X), X0,AA,eps(0)*ones(N-1,1),[],[],X0,[],[],options);

But no success. After exactly N iterations the solution converges to X0.
I used the abs to get Y - AX to minimize to 0, and X0 in the lower bound to satisfy the conditions X0(1) < X(1) etc..
Thanks Shai, using the artificial / dummy objective function, was a great idea. However when I use linprog in the following way :
[X, fval] = linprog( -(1:N), AA, -eps(0)*ones(N-1,1), ...
                         A, Y, X0, [], X0, options );

I get the problem that Y is a scalar and A is still a N x 1 vector. and linprog expects Y to be a vector as well. That changes the problem of course. I set the lower bound to X0, upper bound empty (since the inequality constraint takes care of it), and set the initial values to X0. So still not working. Will update if any resolution occurs.

A: I can see no reason why we cannot find an X for which A*X = Y exactly (there should be enough degrees of freedom for sufficiently large N). So instead of making |A*X-Y| the objective function to be minimize, I suggest adding A*X=Y as a constraint.
Moreover, to encourage Xi < Xj for i<j I suggest an "artificial" objective function -(1:N) that will put larger weight on Xj for large j.
[X, fval] = fmincon( @(X) -(1:N)*X(:), X0, AA, -eps(0)*ones(N-1,1), ...
                                           A, Y, zeros(N,1), ones(N,1), [], options);

And while we are at it, why aren't you using linear programing - this should work better than the general purpose fmincon as it is tailored for the linear case?
[X, fval] = linprog( -(1:N), AA, -eps(0)*ones(N-1,1), ...
                             A, Y, zeros(N,1), ones(N,1), X0, options );


text:
Q: What is the regular expression for this "password"? I want regular expression that contains at least one alphanumeric character, at least one non alphanumeric character (special character) and at least one digit.
Thanks in advance.

A: Correct answer of my question :
regular Expression :
^((?=.[\d])(?=.[a-z])(?=.[A-Z])|(?=.[a-z])(?=.[A-Z])(?=.[^\w\d\s])|(?=.[\d])(?=.[A-Z])(?=.[^\w\d\s])|(?=.[\d])(?=.[a-z])(?=.[^\w\d\s])).{8,30}$
Thanks.

A: So, in other words, at least one alpha, one digit, and one non-alphanum...
You need two lookaheads:
(?=.*[a-zA-Z])(?=.*[0-9]).*[^a-zA-Z0-9]

Since this is marked as homework, I suggest you actually understand it, too:
http://www.regular-expressions.info/lookaround.html

In case you don't want spaces either:
(?=.*[a-zA-Z])(?=.*[0-9]).*(?=\S)[^a-zA-Z0-9]

A: It would be easy to pick out any one of them, but to have all three of them in any order would be something.  You could try a single character of one of the three then use look aheads for the remaining, but you would still need to check behind that character too.

A: Since this is homework (or perhaps not?), here is a hint for a solution that doesn't use look-aheads or other nifty tricks.
In how many (and it what) permutations can the characters occur? How can this be used with the alternation (|) operator?

I would use multiple tests and not a single regex :-)
Happy coding.


text: Q: ProximityAlert management I've a list of GeoPoint that I put on a MapView as interest point. I've added a proximity alert to all of this GeoPoint. I've implemented the onReceive method in the BroadcastReceiver and it works fine. My problem is: how can I get what proximity alert was triggered? I've to implement an AlertDialog with some information about the specific interest point.


text:
Q: Pop up Window using JavaScript The Following code is working fine in firefox. But when it comes to IE 11 I am getting popup window when I close the popup the screen color should change to white but the screen color is not changing to white.
If I click on the page after closing the popup. it becoming white.

var popupWindow = null;

function child_open() {
  popupWindow = window.open("popUp.html", "mywindow", "resizable='yes';scrollbars=yes,toolbar=no,menubar=no,status=no,width=700,height=350");
  document.body.style.backgroundColor = "lightgray"
  document.body.display = 'block';
}

function parent_disable() {
  if (popupWindow && !popupWindow.closed) {
    popupWindow.focus();
  }
  else {
    document.body.style.backgroundColor = "white";
  }

}
<html>

<head>

</head>

<body onFocus="parent_disable();" onclick="parent_disable();" onload="child_open();">

</body>

</html>

What will be the problem.

A: This seems like an issue with IE not focusing the parent back. So the code never runs. Can you try manually focusing the parent body?
window.focus();


text:
Q: Where can I download i686 RedHat 4 bash package? https://rhn.redhat.com/errata/RHSA-2014-1293.html
The offical announce is only starting at RHEL 5. There are no packages for RHEL4? According to Wikipedia, it's still supported until the start of 2015.

A: The entry for RHEL4 on the table on Wikipedia indicates "28 February 2015" as the end of "Extended Life Phase", the end of "Production 3 Phase" was 29 February 2012. During that extended phase, between those dates, there is support  only for customers that "pay an additional subscription" (and that for a subset of packages). This is clearly indicated in the text above the table.
Of course those upgrades during extended life are not freely available. If you are a paying customer contact Red-Hat directly. If you are not a paying customer, and if this is a production server, I suggest upgrading ASAP.

A: As mentioned by Cyrus, you are better off buying an Extended Life Cycle Support licence. The RedHat patch is AFAIK superior to the one provided by Mr.Ramey.

However, the easy way (if you aren't on paid support) is to roll your own bash package:

*

*Install fpm

*Download the source file (http://ftp.gnu.org/gnu/bash/bash-3.0.tar.gz)

*Download all patches (http://ftp.gnu.org/gnu/bash/bash-3.0-patches/)

*tar xzvf bash-3.0.tar.gz

*Apply all patches, including the latest patch -p0 <bash30-019

*./configure --prefix=/usr

*make

*mkdir -p /tmp/bash

*make install DESTDIR=/tmp/bash

*mkdir -p /tmp/bash/bin

*mv /tmp/bash/usr/bin/bash /tmp/bash/bin/bash

*rm /tmp/bash/usr/share/info/dir

*ln -s /bin/bash /tmp/bash/bin/sh

*Add a tmp/bash/etc/skeldirectory with suitable templates

*fpm -s dir -t rpm --epoch 1 -n bash -v 3.0.19 -p bash-3.0.19-1.rpm -C /tmp/bash .

*yum install bash-3.0.19-1.rpm


text:
Q: Proving commutativity of multiplication I am trying to prove Lemma 2.3.2 in Tao's analysis text: that for any two natural number, $n$ and $m$, we have $n \times m = m \times n$. I only have the properties of the natural numbers and addition to work with, along with Tao's definition of multiplication. I have been able to piece together most of the proof, but am struggling with the inductive step.

Proof. Induct on $m$, holding $n$ constant.
Base Case: ($m = 0$) When $m = 0$, we need to prove $n \times 0 = 0 \times n$. The RHS is $0$ by the definition of multiplication. To show the LHS is $0$, we induct on $n$. When $n = 0$, we have $0 \times 0 = 0$ by the definition of multiplication. Our inductive hypothesis is that $n \times 0 = 0$, and need to show that $n++ \times 0 = 0$. By the definition of multiplication, $n++ \times 0 = (n \times 0) + 0$. Using the inductive hypothesis and the properties of addition, we then have  $(n \times 0) + 0 = 0 + 0 = 0$. Thus, our LHS is also $0$.
Induction Hypothesis: Assume $n \times m = m \times n$.
Induction Step: We must show that $n \times (m++) = (m++) \times n$.

I am able to manipulate the right-hand side, but it doesn't seem I am able to do much to the left-hand side.

We have:
\begin{align*}
(m++) \times n & = (m \times n) + n & & \text{Definition of multiplication} \\
& = (n \times m) + n & & \text{Inductive hypothesis} \\
& = (n++) \times m & & \text{Definition of multiplication}
\end{align*}
It doesn't seem I can do anything directly to the LHS without commutativity. My strategy was to manipulate the above into the LHS, but I can't think of where to go next.

Any help would be greatly appreciated.

A: Perhaps we will learn something from showing $1\times n=n\times 1$?
$$1\times n=0{+}{+}\times n =0\times n+n=0+n=n.$$
To show that $n\times 1=n$, we use induction:
$$ 0\times 1=0$$
and
$$ n{+}{+}\times 1=n\times 1+1=n+1=n+0{+}{+}=(n+0){+}{+}=n{+}{+},$$
voila!
Now to the general case. You already showed
$$m{+}{+}\times n=m\times n+n=n\times m+n.$$
So what we need to show is
Claim. $n\times m{+}{+}=n\times m+n$
Proof. (By induction on $n$)
For $n=0$, the claim follows from   $0\times m{+}{+}=0$ and $0\times m+0=0+0=0$.
Now assume $n\times m{+}{+}=n\times m+n$; we want to show $n{+}{+}\times m{+}{+}=n{+}{+}\times m+n{+}{+}$.
We have
$$\begin{align}n{+}{+}\times m{+}{+}&=n\times  m{+}{+}+ m{+}{+} \\&=(n\times m+n)+ m{+}{+}\\&=n\times m+(n+ m{+}{+})
\\&=n\times m+(n+ m){+}{+}
\\&=n\times m+(m+n){+}{+}\\
&=n\times m+(m+n{+}{+})\\
&=(n\times m+m)+n{+}{+}\\
&=n{+}{+}\times m+n {+}{+}\end{align}$$
$\square$


text:
Q: I want to upload file to specific folder with google drive API curl I have uploaded file to google drive with curl API. But I want to upload file to specific folder. I have also tried with folder id in API url like: https://www.googleapis.com/upload/drive/v3/files/folder_id?uploadType=media
add_action('wpcf7_before_send_mail', 'save_application_form');

function save_application_form($WPCF7_ContactForm) {

    $wpcf7 = WPCF7_ContactForm :: get_current();
    $submission = WPCF7_Submission :: get_instance();
    if ($WPCF7_ContactForm->id == 8578) {
        if ($submission) {
            $submited = array();
            //$submited['title'] = $wpcf7->title();
            $submited['posted_data'] = $submission->get_posted_data();
            $uploaded_files = $submission->uploaded_files();
            $name = $submited['posted_data']["Name"];
            $position_test = $submited['posted_data']["Position"];
            $email = $submited['posted_data']["Email"];
            $phone = $submited['posted_data']["phone"];
            $message = $submited['posted_data']["Message"];
            $position = $submited['posted_data']["AttachYourCV"];

           // $test2 = $_FILES['AttachYourCV']['name'];

            $finfo = finfo_open(FILEINFO_MIME_TYPE);
            $cf7_file_field_name = 'AttachYourCV';

            $image_location = $uploaded_files[$cf7_file_field_name];
            $mime_type = finfo_file($finfo, $image_location);
            $token = GetRefreshedAccessToken('client_id', 'refresh_token', 'client_secret');
            $ch = curl_init();
            curl_setopt_array($ch, array(
                CURLOPT_URL => 'https://www.googleapis.com/upload/drive/v3/files?uploadType=media',
                CURLOPT_HTTPHEADER => array(
                    'Content-Type:' . $mime_type, // todo: runtime detection?
                    'Authorization: Bearer ' . $token
                ),
                CURLOPT_POST => 1,
                CURLOPT_POSTFIELDS => file_get_contents($image_location),
                CURLOPT_RETURNTRANSFER => 1
            ));
            $response = curl_exec($ch);
            $id = json_decode($response, TRUE);
            $get_id = $id['id'];

    curl_close($ch);
   if (isset($id['id'])) {
            $get_id = $id['id'];
            $post_fields = array();
            $folder_id = '1-9r8oVsAfV_iJmYh1cZYPMvE9Qhv8RLA';
            // remove extension
            $this_file_name = explode('.', $position);

            // submit name field
            $post_fields['name'] .= $this_file_name[0];
            $post_fields['parents'] = $folder_id[1];
            $ch2 = curl_init();
            curl_setopt_array($ch2, array(
                CURLOPT_URL => 'https://www.googleapis.com/drive/v3/files/' . $get_id,
                CURLOPT_HTTPHEADER => array(
                    'Content-Type:application/json', // todo: runtime detection?
                    'Authorization: Bearer ' . $token
                ),
                CURLOPT_POST => 1,
                CURLOPT_CUSTOMREQUEST => 'PATCH',
                CURLOPT_POSTFIELDS => json_encode($post_fields),
                CURLOPT_RETURNTRANSFER => 1
            ));
            $response = curl_exec($ch2);
            if ($response === false) {
                $output = 'ERROR: ' . curl_error($ch2);
            } else {
                $output = $response;
            }

            // close second request handler
            curl_close($ch2);

        }
}

I have added another curl call but still didn't get file in folder. My file untitled issue solved with this way.

A: Uploading files to google drive is a two part thing. (note it can be done as a single call but if you want to add the corect data its best to do it as two)
create Adds the initial meta data for the file. Name, media type, and location that being its parent directory.
Second the actual upload of the file itself.
Note: a file uploaded without first sending the metadata will create a dummy metadata most often with a title of the file being "unknown."
Create
When you do your create of the inertial metadata. You need to add the parents in this inital call the field is called parents[] you need to add the file id there.   I cant help you do this as your not adding the code for it.
Upload
By default the file is uploaded into the root folder unless you add a parent folder id for the file.
If you check the documentation you will find the optional query parms

Try using &addParents=[folderId]
Example:
https://www.googleapis.com/upload/drive/v3/files?uploadType=media&addParents=1bpHmln41UI-CRe5idKvxrkIpGKh57T32

If you originally created the metadata for the file in the root directory and then try to upload the file to a different directory i suspect that the upload will create new metadata.  These two calls need to be done the same.  Your create should have parents set.
post body
$data = array("name" => "test.jpg", "parents" => array("123456"));
$data_string = json_encode($data);

curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);


text:
Q: Adding views programmatically with a xml layout I want to programmatically add a view to ScrollView that is apart of a Fragment layout.
I have attempeted the following code:
public class MessageDetail extends Fragment {

    View layout;
    TextView messageText;
    Conversation conversation;
    List<Message> messages;
    LayoutInflater inflater;
    ViewGroup container;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        this.inflater = inflater;
        this.container = container;
        layout = inflater.inflate(R.layout.messenger_detail, container,
                false);
        messageText = (TextView) layout.findViewById(R.id.tvMessage);

        return layout;

    }

    public void loadConversation(Conversation conversation) {

        messageText.setText(conversation.getSubject());

        LinearLayout messagesView = (LinearLayout)layout.findViewById(R.id.llMessageDetail);

        LinearLayout messageBody = new LinearLayout(getActivity());
        View body = inflater.inflate(R.layout.messagebody, container);

        messagesView.addView(body);

    }

}

messagebody.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/llMessageBody"
    android:layout_width="fill_parent"
    android:layout_margin="5dp"
    android:layout_height="200dp"
    android:background="#353535"
    android:orientation="vertical" >
    <TextView
        android:id="@+id/tvMSBodyFrom"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20dp"
        android:text="Research Station:"
        android:textColor="#FFFFAA"
        />
<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/tomatohigh"
    />
</LinearLayout>

message_detail.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#d3d6da"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="100dp"
        android:background="#FFAA00" >

        <TextView
            android:id="@+id/tvMessage"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginLeft="20dp"
            android:text="Select a Message:"
            android:textColor="#353535"
            android:textSize="30dp" />
    </LinearLayout>

    <ScrollView
        android:id="@+id/svMessageDetail"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="#9900AA"
        android:minHeight="300dp" >

        <LinearLayout
            android:id="@+id/llMessageDetail"
            android:layout_width="fill_parent"
            android:orientation="vertical"
            android:layout_height="wrap_content" >

        </LinearLayout>
    </ScrollView>

</LinearLayout>

The final implementaion would see me loop through a list of messages and add the a view with the message_body layout and change each part of the layout to the correct values of each message
Any ideas how to achieve this?

A: You can do like this:
YourView varView = new YourView(this);
myButton.setLayoutParams(new YourLayout.LayoutParams());

yourParentLayout.addView(varView);

Example: Add a button in parent linear layout
Button myButton = new Button(this);
myButton.setLayoutParams(new LinearLayout.LayoutParams(
                                     LinearLayout.LayoutParams.FILL_PARENT,
                                     LinearLayout.LayoutParams.FILL_PARENT));

myLayout.addView(myButton);


text:
Q: Codeigniter 4 customized route is showing me a 404 error i'm using CodeIgniter 4 and having trouble creating a route
I have this url
/Show/post/100008
But I want to route it to this
/post/100008
I've tried
$routes->get('/post/(:num)', 'Show::post/(:num)');
but i'm getting 404 error when typing /post/100008 url only
Is the route correct or is there any other solution for it?
Thank you

A: The solution is by changing the line to
$routes->get('/post/(:num)', 'Show::post/$1');
Codeigniter 4 URI Routing docs : https://codeigniter.com/user_guide/incoming/routing.html