text:
Q: Unable to Upgrade my android code to gradle 3.5.3 while using android-apt I am unable to upgrade code to gradle 3.5.3 when I tried a lot of error occurs.
here my old code app.gradle
apply plugin: 'com.android.application'
apply plugin: 'android-apt'
apply plugin: 'me.tatarka.retrolambda'

android {
    compileSdkVersion 25
    buildToolsVersion '25.0.3'
    defaultConfig {
        applicationId "com.fiapps.alquran.tafseer"
        minSdkVersion 14
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        multiDexEnabled true
    }

    buildTypes {
        release {
            minifyEnabled true
            shrinkResources true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }

        debug {
            minifyEnabled true
            shrinkResources true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

apt {
    arguments {
        androidManifestFile variant.outputs[0].processResources.manifestFile
        resourcePackageName android.defaultConfig.applicationId
    }
}

dependencies {
    apt "org.androidannotations:androidannotations:3.2"
    compile "org.androidannotations:androidannotations-api:3.2"
    compile 'com.android.support:appcompat-v7:25.4.0'
    compile 'com.android.support:support-v4:25.4.0'
    compile 'com.squareup:otto:1.3.8'
    compile 'com.astuetz:pagerslidingtabstrip:1.0.1'
    compile 'org.apache.commons:commons-lang3:3.4'
    compile 'commons-io:commons-io:2.4'
    compile 'com.koushikdutta.ion:ion:2.1.8'
    compile 'com.google.code.gson:gson:2.8.2'
}

and this old project.gragle
// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.3'
        classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
        classpath 'me.tatarka:gradle-retrolambda:3.7.0'
    }
}

allprojects {
    repositories {
        jcenter()
        google()
    }
}

repositories {
    mavenLocal()
    mavenCentral()
}

my updated code app.gradle but still give a lot of issues
apply plugin: 'com.android.application'
apply plugin: 'me.tatarka.retrolambda'

android {
    compileSdkVersion 28
    buildToolsVersion '28.0.3'
    defaultConfig {
        applicationId "my.package.here"
        minSdkVersion 14
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        multiDexEnabled true

        javaCompileOptions {
            annotationProcessorOptions {
                includeCompileClasspath = true
            }
        }

        applicationVariants.all { variant ->
            variant.variantData.variantConfiguration.javaCompileOptions.annotationProcessorOptions.arguments =
                    ['androidManifestFile': variant.outputs[0]?.processResources?.manifestFile?.absolutePath,
                     'resourcePackageName': android.defaultConfig.applicationId]
        }

    }
    buildTypes {
        release {
            minifyEnabled true
            shrinkResources true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }

        debug {
            minifyEnabled true
            shrinkResources true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

}
dependencies {
    implementation "org.androidannotations:androidannotations:4.6.0"
    implementation "org.androidannotations:androidannotations-api:4.6.0"
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    implementation 'com.squareup:otto:1.3.8'
    implementation 'com.astuetz:pagerslidingtabstrip:1.0.1'
    implementation 'org.apache.commons:commons-lang3:3.9'
    implementation 'commons-io:commons-io:2.6'
    implementation 'com.koushikdutta.ion:ion:2.2.1'
    implementation 'com.google.code.gson:gson:2.8.6'
    implementation 'com.google.dagger:dagger:2.25.4'
    annotationProcessor 'com.google.dagger:dagger-compiler:2.25.4'
    annotationProcessor 'com.google.auto.value:auto-value:1.7'

}

and this updated project.gragle
// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
        mavenCentral()
        google()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.5.3'
        classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
        classpath 'me.tatarka:gradle-retrolambda:3.7.0'
    }
}

allprojects {
    repositories {
        jcenter()
        google()
    }
}

repositories {
    mavenLocal()
    mavenCentral()
}

I tried a  lot of code from stack but did not successed please how to resolve issue, please

A: I just added below line in app gradle now it's working here is full discussion.
  annotationProcessor "org.androidannotations:otto:4.6.0"


text:
Q: Logic formal proofs find the derived statements 1.(K•L)>M
2. K>L
Therefore K>[(K•L)•M]
3. K>(K•L) 2,Abs.
4.
5. K>[(K•L)•M]
 This is what I have so far but I don't know if I started Off right can you please help me?

A: If you can use a conditional proof this is quite easy. Just asume $K$ and then you can derive $L$ from $2$. Then you would have $K \wedge L$ to derive $M$ from $1$. From there you can get $(K \wedge L) \wedge M$ and discharge with  $K \rightarrow ((K \wedge L) \wedge M).$ However a direct proof is by no means obvious. Here is a direct proof:
$1. (K \wedge L) \rightarrow M \\
2. K \rightarrow L  \vdash  K \rightarrow ((K \wedge L) \wedge M)) \\
3. K \rightarrow (K \wedge L) \quad (2 \, Absorption) \\
4. K \rightarrow M \quad (1,3 \, Hypothetical \, Syllogism) \\
5. \neg K \vee  (K \wedge L) \quad (3 \, Material \, Implication) \\
6. \neg K \vee M \quad (4 \, Material \, Implication) \\
7. (\neg K \vee (K \wedge L)) \wedge (\neg K \vee M) (5,6 \, Conjunction ) \\
8. \neg K \vee ((K \wedge L) \wedge M) \quad (7 \, Distribution) \\
9. K \rightarrow ((K \wedge L) \wedge M) \quad (8 \, Material Implication)$

redpajama_set_name: RedPajamaStackExchange


text:
Q: Identify the View that triggered a touch-event I am trying to drag a view over the screen
FrameLayout main = (FrameLayout) findViewById(R.id.main_view);
final Ball bigball;
bigball = new Ball(this,50,50,25, 0xFFFF0000);
main.addView(bigball);

This draws a red circle on my screen. How and where do I need to implement my touchscreen-handling, if I want it only to trigger if someone touches the red circle rather than the remainder of the screen?
Ball.Java is a separate class:
public class Ball extends View

I know I could check the coordinates where the user touched the screen and then compare that to where the circle is, but there must be a way to simply check the ID or some other reference of the circle, right?
Everything I have looked at and tried so far would run my code regardless of where the touch started or stopped on the screen. (So I can move the ball, I can draw lines on the screen with my finger and everything. But I cannot tell if I touched the red circle.)
Can anyone expain this to me in simple words, please? (And forgive me for using equally simple words in my question. I no longer feel I have a clue what I'm doing here, and I by now I would just not use big words like "Listener" or "Event" correctly anymore.
Thanks.

A: you can override/implement onTouchEvent in Ball class which is extended from View.public class Ball extends View {
  public boolean onTouchEvent(MotionEvent ev) {
    if(ev.getAction == /*check against all the desired action*/ {
      //handle touch and return true
    return super.onTouchEvent(ev);
}


text:
Q: Verilog Syntax Error It's verilog code and can't simulate because of syntax error. Anyone know how to solve it?
assign x = (Status == 2'b00)?
{Board[0],1'b0,1'b0,Board[2],1'b0,1'b0,Board[1],1'b0,Board[3],1'b0,1'b0,Board[5],1'b0,1'b0,Board[4],1'b0,1'b0,Board[6],1'b0,1'b0,Board[8],1'b0,1'b0,Board[7],1'b0,Board[9],1'b0,1'b0,Board[11],1'b0,1'b0,Board[10],1'b0,Board[12],1'b0,1'b0,Board[14],1'b0,1'b0,Board[13],1'b0,Board[15],1'b0,1'b0,Board[17],1'b0,1'b0,Board[16],1'b0}:

(Status == 2'b01)?
64'b0110000001100000011000000110000000000000000000000000000000000000:

(Status == 2'b10)?
64'b1101101011011010110110101101101000000000000000000000000000000000:

(Status == 2'b11)?
64'b1001110011101111011100100100000100000000000000000000000000000000:

A: Form minimum code change:
//(Status == 2'b11)?// <- comment out for final condition
64'b1001110011101111011100100100000100000000000000000000000000000000 ; // <- semicolon, not colon
Better yet convert to a case statement. Easier to read and debug.
reg [63:0] x;
always @* begin
  case(Status)
  2'b00: x = ... ;
  2'b01: x = ... ;
  2'b10: x = ... ;
  2'b11: x = ... ;
  endcase
end

A: x= (condition==2'b00)? a:(condition==2'b01)?:b:(condtion==2'b10)?:c:(condtion==2'b11)?:d

This is how your code looks when the values for assigning to x are replaced with a,b,c,d.The statement will definitely throw an error as you have clearly violated the way ternary operator is supposed to be used.
Ternary operator syntax:
x=(condition)?a:b

If the condition is true, x will be assigned the value of a.
If the condition is false, x will be assigned the value of b.
Ternary operator syntax if used in a nested way:
x=(condition1)?a:((condition2)?b:c)

If the condition1 is true, x will be assigned the value of a.
If the condition1 is false, it will check for condition2. If condition2 is true, x will be assigned the value of b else x will be assigned the value of c.
Looking at your code, you have repeated colons at inappropriate places.
x= (condition==2'b00)? a:(condition==2'b01)?:b:(condition==2'b10)?:c:(condition==2'b11)?:d
                                            ^                     ^

There should not be a colon after the question mark.
Probably you can rewrite the condition as:
assign x= (condition==2'b00)?a:(condition==2'b01)? b:(condition==2'b10)?c:d;

Look at the small verilog code that helps in understanding the working of nested ternary operator:
Verilog code
Hope my code helps you!

A: You havent posted any specific error message.
A good way of Debugging :
Use $Display("any text") near line numbers that are pointed out as errors in the code by the compiler. From the code it seems you are doing a lot of Vector part Select. Case statement is a better choice.


text:
Q: Caesar Cipher bruteforce This is my class exercise we have to brute force the follow "hdvb wr euhdn" and find the key that works, but my code breaks it (I think correctly) but two different keys produce the same outcome. Is this normal or am I doing it wrong?
Key 2 and 11 work, and a few others that don't work still repeat the same characters. We just covered basic Caesar shift ciphers and I figured this approach was the best brute force .

#include<iostream>
#include<String>

using std::string;
using std::endl;

void bruteForce(string x);

void bruteForce(string x)
{

    int key = 0;

    int length = (int)x.length();

    for (int i = 0; i < 25; i++)
    {
        key++;
        std::cout << "The key is  " << key << endl;
        std::cout << endl;
        for (int j = 0; j < length; j++)
        {

            if (x[j] == ' ')
            {
                x[j] = ' ';
                std::cout << x[j];
                j++;
            }
            x[j] = tolower(x[j]);
            x[j] -= 97;
            x[j] -= key;
            if (x[j] < 0)
            {
                x[j] += 26;

            }
            x[j] += 97;

            std::cout << x[j];
        }

        std:: cout << endl;

    }

}

A: Each loop is modifying the input as mentioned by Alexander O'Mara - refactor to separate the key change from the test.
Declare a function for the testing (separate to brute-force)
void Test(std::string x, int key);

Call it from bruteForce.
void bruteForce(string x)
{

    int key = 0;

    for (int i = 0; i < 25; i++)
    {
        key++;
        Test( x, key );
    }
}

Implementation
void Test(std::string x, int key)
{
    int length = (int)x.length();
    std::cout << "The key is  " << key << endl;
    std::cout << endl;
    for (int j = 0; j < length; j++)
    {
        if (x[j] == ' ')
        {
            x[j] = ' ';
            std::cout << x[j];
        }
        else {
            x[j] = tolower(x[j]);
            x[j] -= 97;
            x[j] -= key;
            if (x[j] < 0)
            {
                x[j] += 26;

            }
            x[j] += 97;
        }
        std::cout << x[j];
    }

    std::cout << endl;

}

I slightly changed your skip for space, so that 2 spaces in a row, wouldn't confuse it.
The code works because each call to Test is a new copy of the pristine string.  Each successive key for a cesear cypher shifts by one character, so that should have alerted you to the re-use of the string.

A: You can simply use the following function to decrypt the Caesar cipher code
void decrypt(char arr[],int key){
int i,j;
for(i=0;i<strlen(arr);i++){
    if(arr[i]==' ')
        continue;
    for(j=0;j<key;j++){
        arr[i]--;
        if(arr[i]<97 && arr[i] > 90)
            arr[i] = 122;
        if(arr[i] < 65)
            arr[i] = 90;
    }

}}

To brute force, you can simply put the above function into a for loop which will iterate from 1 to 26 providing all the 26 possible keys to the decrypt function. Below is the example
int main(){
int i;
char arr[100],copy[100];
printf("Enter a string: ");
scanf ("%[^\n]s", arr);
strcpy(copy,arr);
for(i=1;i<=26;i++){
    encrypt(arr,i);
    printf("Bute Force key : %d ---> %s\n",i,arr);
    strcpy(arr,copy);
}}

Encrypt Function source : C program to implement Caesar Cipher Algorithm


text:
Q: Lottery probability question, matching integers The question is:

In LOTTO $49$, Michigan's lottery game, a player selects $6$ integers out of the first $49$ positive integers. The state then randomly selects $6$ out of the first $49$ integers. Cash prizes are given to a player who matches $4, 5$, or $6$ integers. Let $X$ be the number of integers selected by a player that match integers selected by the state. Find $P(X = 1)$.

The answer is: $.413$
I'm not sure where to start. I thought about doing ${49 \choose 6}$ to represent the numbers the state chooses. But I'm not sure what do from there to see what the probability is that a player chooses exactly $1$ integer that matches.

A: $6$ numbers are lucky numbers, $43$ of them are not.
Hence $$P(X=1)=\frac{\binom{6}{1}\binom{43}{5}}{\binom{49}{6}}.$$


text:
Q: Syntax error for optional pattern, but only in debugger This expression (explained here by Leonid) evaluates fine unless Evaluation->Debugger is enabled:
h[x : (_Integer) : 1] := x

Syntax::sntxf: "x:" cannot be followed by "(_Integer):1".
  Syntax::tsntxi: "(_Integer):1" is incomplete; more input is needed.
  Syntax::sntxi: Incomplete expression; more input is needed .

Strangely it works if the parentheses are removed:
h[x : _Integer : 1] := x

But both of these fail when debugging:
h[x : (_Integer | None) : None] := x
h[x : Alternatives[_Integer, None] : None] := x

(* Workaround: *)
ptn = _Integer | None;
h[x : ptn : None] := x

All this was with Mathematica 8.0.4 Linux
What is the debugger up to?


text:
Q: How to check session without creating new one? In part of my application i have some custom settings for visitors.
When user load page i try to check custom settings for request and if settings exist i do customization in page.
i do it in Template Context Processor
def shared_values(request):

    show_help = request.session.get('show_help', True)
    return {
        'show_help': show_help,
    }

It's work perfect, but i have problem - each time, when i check session django create new entry in Session table if entry does not exist before.
How can i check session without creating new one?
Edit 1:
Then i disable checking for session key, i see what django does not create any Session entry for requests.

*

*I login as admin in 1st browser (chrome) and delete all session (except one for mydself)

*Edit context processor, so i don't access sessions in my project:
show_help = True

*Open page in different browser (firefox)

*Switch to 1st browser and check if new session object is appear, but nothing has changed - only one session object exist.
Edit 2:
i use django 1.4.1

A: Docs:

When SessionMiddleware is activated, each HttpRequest object – the
  first argument to any Django view function – will have a session
  attribute, which is a dictionary-like object.

So every time you make request - session will be created, if it does not exists already.
When context_processor is applied - session already exists. You should not worried about that.


text:
Q: Is my scala Regex pattern is the correct way to represent? val pass = "123 Enter right number from (10,5,3,3,200,6)"
 val pattern = """\d+,\d+,\d+,\d+,\d+,\d+""".r
val pp = pattern.findfirstIn(pass)
println(pp)

Yes I got it extracted as
10,5,3,3,200,6

which is what i needed
My question is, is this
val pattern = """\d+,\d+,\d+,\d+,\d+,\d+""".r

the correct way to represent regex pattern....?

A: Yes, certainly. However, you can do some really cool stuff with it involving Scala's pattern matching if you enhance your pattern with capturing groups:
val pattern = """.*?(\d+),(\d+),(\d+),(\d+),(\d+),(\d+).*?""".r
val pattern(d0, d1, d2, d3, d4, d5) = pass


text:
Q: Can I update an INT value + 1 and return the new value? Is it possible in MySQL+PHP to increase an INT value and return the new value within one query?
$sql = mysql_query("UPDATE table SET number=number+1 WHERE id='uniqid'");

$updated_number = ???

Or I need to post another query?
SELECT number FROM table WHERE id='uniqid'

A: Simple answer - no, it's not possible.
Longer answer, yes, if you use a stored procedure that increments the value for the specified ID, retrieves the new value and returns it.
I've just tested this under MySQL 5.1.59:
CREATE PROCEDURE increment (IN uniqid VARCHAR(255))
BEGIN
   UPDATE `table` SET number = number + 1 WHERE id = uniqid;
   SELECT number FROM `table` WHERE id = uniqid;
END

Usage:
CALL increment(uniqid)

If multiple simultaneous accesses are possible you may wish to LOCK the table first to ensure the operation's atomicity - MySQL apparently doesn't allow stored procedures to lock tables themselves.

A: No. You will need to select that line afterwards

A: There is way without procedure. You can store new value in session variable and get it from next statement.
UPDATE table SET number = (@next_value := number + 1) WHERE id = 'uniqid';
ant then:
SELECT @next_value;
Your session variable is not affected by other increments.

A: @luvPlsQL is right. But basically you need to get the data first, next increase it and then update. At last you got the increased variable before update so you can use it.

A: you can do
status = mysql_query(mysql,
                     "UPDATE table SET number=number+1 WHERE id='uniqid';\
                      SELECT FROM table WHERE id='uniqid';\
                     ");

and use  mysql_next_result() to get the results.


text:
Q: How to insert value in multiple row by a single user submit using PHP,Angular.js and MySQL I need to insert multiple rows in a single user click using Angular.js and PHP. First I am explaining my code below.
time.html

    Time

Day

              <select id="coy" name="coy" class="form-control" ng-model="sub_name " ng-options="sub.name for sub in listOfSubjectName track by sub.value">
              </select>

              <select id="coy" name="coy" class="form-control" ng-model="fac_name " ng-options="fac.name for fac in listOfFacultyName track by fac.value">
              </select>

The above part of code is giving the following output on the UI. Click on below link see the output image.
Time table
timecontroller.js
$http({
    method: 'GET',
    url: "php/timetable/gethour.php",
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(function successCallback(response){
        //console.log('hour',response.data);
        $scope.hours=response.data;
    },function errorCallback(response) {
});
$http({
    method: 'GET',
    url: "php/timetable/getdays.php",
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(function successCallback(response){
   $scope.days=response.data;
        // console.log('days',$scope.days);
        for (var i = 0; i < 5; i++) {
         $scope.noOfDays.push($scope.days[i]);
     }
 },function errorCallback(response) {
 });

In the above image, you can see I have 5 days and some time slot. I need here when user will click on any submit button all selected course name data, faculty name data, day time slot will save in database. Let me to given one example. Suppose user clicked on submit button in first row it will save monday,09AM :: 10AM,course name,faculty name again in second row it will save monday,10AM :: 11AM,course name,faculty name and so on. Like this way it will insert 5*7=35 row in one click. Please help me to do this.

A: When I look at your code I see you bind the select boxes to "sub_name" and "fac_name". I haven't tested it, but I think changing one "sub_name" will update all of the "sub_name" select's, as they are all bound to the same models.
First you will need to tackle this. I would make one big model (called "roster") and have each day/simeslot in that model.
var roster = {
    monday:[
        {
            startTime: 9,
            endTime: 10,
            cource: 'courcename',
            faculty: 'faculty name'
        },
        {
            startTime: 10,
            endTime: 11,
            cource: 'courcename2',
            faculty: 'faculty name2'
        },
        .......
    ]
}

Than you can watch this model, and when it changes do your http calls to update the DB. You could also figure out what values actually changed and only push these changes to the database.


text:
Q: Reuse HTML element by referencing its ID I am showing a list of items, with an expander that summarizes that item.  If the user chooses to delete the item, I need to show a confirmation modal with the same summary.  I would like to not recreate the HTML summary (needs to be identical), but to reshow the content by referencing the ID of that element.
Can this be done without causing some conflict because essentially there will be 2 elements with the same ID in the DOM?
Thanks

A: As stated luissimo, you need to use a class. Using 2 same IDs is wrong. It will work but it's false. So my opinion is the same as luissimo.


text:
Q: Angular - Undefined Values in subscribe return I am developing a form, where I will get value from a webapi and show to user.. Ok.. all part os get data from webapi are ok. Subscribe are returning the right Json, without problem
this is the angular program:
import { Component, Input, ViewChild, OnInit } from '@angular/core';

import { ErrorMsgComponent } from '../../shared/error-msg/error-msg.component';

import { UserallService } from 'src/app/services/userall.service';
import { Router } from '@angular/router';
import { UserAll } from '../../interfaces/userall';

import {NgForm} from '@angular/forms';

@Component({
  selector: 'app-userdet',
  templateUrl: './userdet.component.html',
  styleUrls: ['./userdet.component.css']
})
export class UserdetComponent implements OnInit {
  @Input() userall: UserAll =  {} as UserAll;
  @ViewChild(ErrorMsgComponent) errorMsgComponent: ErrorMsgComponent;
  @ViewChild('f', {static: false}) myForm: NgForm;

  public isDisabled = true;
  public btnName = 'Alterar dados';
  private userallOld = this.userall;

  constructor(private userAllService: UserallService, private router: Router) {
  }

  ngOnInit(): void {
    this.getUserData();
  }

  public editarForm(): void {
    this.isDisabled = !this.isDisabled;

    if (this.isDisabled) {
      this.userall = this.userallOld;
      this.btnName = 'Alterar dados';
    }
    else {
      this.btnName = 'Cancelar';
    }
  }

  onSubmit(): void {
    this.modUserAll(this.userall);
  }

  modUserAll(userall: UserAll): void {
    this.userAllService.modUserAll(userall)
      .subscribe(
      () => {
        this.errorMsgComponent.setOk('Usuário alterado com Sucesso');
        this.myForm.resetForm();
      },
      error => {
        console.log(error);
        this.errorMsgComponent.setError('Falha ao alterar usuario.');
      });
  }

  getUserData(): void {
    this.userAllService.getUser(sessionStorage.getItem('currentUserId'))
      .subscribe(
      (result: UserAll) => {
        this.userall = result;
        console.log(result);
        console.log(result.name);
        console.log(sessionStorage.getItem('currentUserId'));
        console.log(this.userall.name);
        this.myForm.name = this.userall.name;
      },
      error => {
        console.log(error);
        this.errorMsgComponent.setError('Falha ao ler dados do usuario.');
      });
  }
}

this is the instance for userall:
export interface UserAll {
  id: number;
  name: string;
  address1: string;
  address2: string;
  city: string;
  country: string;
  zipCode: string;
  phoneNumber: string;
 }

and this is the returns from console log..
console.log(result);

[{…}]0:
address1: "xxxxxxxx"
address2: "yyyyyyy"
city: "fffffffffff"
country: "Brazil"
id: 1
name: "sjh fsdkjfh sakjhf "
phoneNumber: "+5531969696969"
user: null
userId: "380de5fe-711a-4b4a-9130-4c86684c38df"
zipCode: "6969696969"
proto: Objectlength: 1__proto__: Array(0)

    console.log(result.name);

userdet.component.ts:67 undefined
    console.log(sessionStorage.getItem('currentUserId'));

userdet.component.ts:68 380de5fe-711a-4b4a-9130-4c86684c38df
    console.log(this.userall.name);

userdet.component.ts:69 undefined
i am confuse, because the json are returned by the subscribe, but the result.name is undefine.. WTH?

A: It seems this is an array with objects returned. Try result[0].name


text:
Q: Can I check the current value in an IPython magic command (%xmode)? I want to check the current value of a magic command %xmode. The available mode is Context, Plain, and Verbose.
If you just type in %xmode, then it automatically switches to the next value. Certainly, you can know which value it was set to, but it is a pain to run the same command two more times to set it back to the original value.
So is it possible to only chech the value, without changing it?

A: We can run the following line to get the current xmode from an IPython terminal
get_ipython().config['InteractiveShell']['xmode']


text:
Q: Datepicker in AJAX loaded Modal I can successfully initialize the datepicker every time the modal is loaded. What I cannot do, is to get it working to complete the input field.
My logic is the following:

*

*Write Modal on page load

*Fill in with AJAX reques

*Activate DatePicker

The content to be loaded is a form.
The first time it runs, it works like a charm. From the second time on, it doesn't complete the input field once it has been selected.
It's not an ID problem, since the input id is created dinamically and datepicker is loaded by class.
This is my initialization code:
$.each($html.find('.datepicker'), function(){
    var $input = $(this);
    return $input.datepicker('destroy').datepicker({
        dateFormat: 'yy-mm-dd',
        changeMonth: true,
        showButtonPanel: true,
        minDate: -1,
        maxDate: "+1D +1Y",
        onClose: function(selectedDate){
            $input.addClass('has-success');
        }
    });
});

As you can see I used .addClass('has-success') to easilly locate the input which was updated... but no input is ever updated from the second load of the modal on.
Any thoughts?

A: You should use this construction of jQuery-each:
$.each($html.find('.datepicker'), function(index, value) {
    var $input = value;
    return $input.datepicker('destroy').datepicker({
        dateFormat: 'yy-mm-dd',
        changeMonth: true,
        showButtonPanel: true,
        minDate: -1,
        maxDate: "+1D +1Y",
        onClose: function(selectedDate){
            $input.addClass('has-success');
        }
    });
});

OR
$html.find('.datepicker').each(function() {
    var $input = $(this);
    return $input.datepicker('destroy').datepicker({
        dateFormat: 'yy-mm-dd',
        changeMonth: true,
        showButtonPanel: true,
        minDate: -1,
        maxDate: "+1D +1Y",
        onClose: function(selectedDate){
            $input.addClass('has-success');
        }
    });
});

A: I wrote code like this and work properly in multiple field form:
Add this code before loop:
<link rel="stylesheet" href="//code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css"/>

And this line is in loop:

     Input Date
    <input name="myDate$i" type="text" class="form-control mydatepicker" id="myDate$i" required ="true" placeholder="Contoh: 2022-11-25" data-bs-toggle="tooltip" style="border-radius: 3px; padding:10px;"/>


text:
Q: Why is this Hilbert curve not drawing? import turtle as t
t.setup(500,500)
t.setworldcoordinates(0,0,500,500)
t.pu()
t.goto(0,0)
t.pd()
t.seth(0)
def N():
    t.pu()
    t.pd()
def B(c,d):
    t.right(90)
    c
    t.forward(5)
    t.left(90)
    d
    t.forward(5)
    d
    t.left(90)
    t.forward(5)
    c
    t.right(90)
def A(a,b):
    t.left(90)
    b
    t.forward(5)
    t.right(90)
    a
    t.forward(5)
    a
    t.right(90)
    t.forward(5)
    b
    t.left(90)
t.seth(0)
A(A(None,None),B(None,None))

I'm trying to make a Hilbert curve but it is not working.
I am using the L-system

A: Your code is passing functions to other functions but isn't calling them correctly (you need parentheses and arguments.)  My best guess at patching this code is as follows:
from turtle import Screen, Turtle

def A(a, b, n):

    if n == 0:
        return

    turtle.left(90)
    b(a, b, n - 1)
    turtle.forward(5)
    turtle.right(90)
    a(a, b, n - 1)
    turtle.forward(5)
    a(a, b, n - 1)
    turtle.right(90)
    turtle.forward(5)
    b(a, b, n - 1)
    turtle.left(90)

def B(c, d, n):

    if n == 0:
        return

    turtle.right(90)
    c(c, d, n - 1)
    turtle.forward(5)
    turtle.left(90)
    d(c, d, n - 1)
    turtle.forward(5)
    d(c, d, n - 1)
    turtle.left(90)
    turtle.forward(5)
    c(c, d, n - 1)
    turtle.right(90)

screen = Screen()
screen.setup(500, 500)
screen.setworldcoordinates(0, 0, 500, 500)

turtle = Turtle()

A(A, B, 7)

screen.exitonclick()


text:
Q: Problem with AJAX and PHP! I have a PHP page that will collect mp3 links from downloads.nl. The result is converted to XML and renders fine.
The problem occurs when I try to read that XML using ajax. The files are on the same domain and it's really confusing me. This is my php crawler.
    <?php
header("Content-type: text/xml");
$artistname = $_GET['artistname'];
$trackname = $_GET['trackname'];
$newartistname = str_replace(" ","+",$artistname);
$newtrackname = str_replace(" ","+",$trackname);
$target_url = "http://www.downloads.nl/results/mp3/1/".$newartistname."+".$newtrackname;
$userAgent = 'Googlebot/2.1 (http://www.googlebot.com/bot.html)';
error_reporting(0);

// make the cURL request to $target_url
$ch = curl_init();
curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$html= curl_exec($ch);
if (!$html) {
    echo "
cURL error number:" .curl_errno($ch);
    echo "
cURL error:" . curl_error($ch);
    exit;
}

// parse the html into a DOMDocument
$dom = new DOMDocument();
@$dom->loadHTML($html);

// grab all the on the page
$xpath = new DOMXPath($dom);
$hrefs = $xpath->evaluate("/html/body//a");
echo '<?xml version="1.0"?>';
echo '<downloads>';
echo '<trackname>'.$newartistname."+".$newtrackname.'</trackname>';
for ($i = 0; $i < $hrefs->length; $i++) {
    $href = $hrefs->item($i);
    $url = $href->getAttribute('href');
        if(strpos($url, ".cgi")){
            echo '<link>http://downloads.nl'.htmlspecialchars($url,ENT_QUOTES).'</link>';
          }
}
echo '</downloads>';
?>

and here is my javascript function
 function getDownloadLink(artistname,trackname){
        var xmlhttp4;
        if (window.XMLHttpRequest){
            xmlhttp4 = new XMLHttpRequest();
        }
        else{
            xmlhttp4 = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp4.onreadystatechange=function(){
            alert(xmlhttp4.readyState);
            if (xmlhttp4.readyState==4 && xmlhttp4.status==200){
                try{
                    var downloadlink = xmlhttp4.responseXML.documentElement.getElementsByTagName("downloads");
                    for (var i=0;i<downloadlink.length;i++){
                        alert(i);
                    }
                }
                catch(er){
                    alert(xmlhttp4.responseText);
                }
            }
            else{
                alert("ReadyState: "+xmlhttp4.readyState+" Status: "+xmlhttp4.status);
            }
        }
        xmlhttp4.open("GET","http://localhost/bone/searchmusic.php?artistname="+artistname+"&trackname="+trackname,true);
        xmlhttp4.send(null);
    }

I have no idea what the problem is. Am I not rendering the XML correctly or is my ajax lacking?
Thanks,
Sam

A: The following page, using the jQuery JavaScript framework, is working for me…
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

    <title>Test</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

    Get Lady GaGa - Bad Romance tracks

…given that you have a file called downloads.xml file in the following format:
<?xml version="1.0"?>
<downloads>
  <trackname>LadyGaga+BadRomance</trackname>
  <link>a</link>
  <link>b</link>
  <link>c</link>
  <link>d</link>
</downloads>

This code doesn't actually use the artist and track but I added them to give you an idea of how it might work.

A: Thanks for you solution Andyb. It works like a charm now. I had a look at jQuery Ajax before but never thought it wasn't powerful enough. Here is the code that I'm using right now.
    function getDownloadLink(artist, track) {
        $.ajax({
            url:'http://localhost/bone/searchmusic.php?artistname='+artist+'&trackname='+track,
            dataType:'xml',
            success: function(xml) {
                $(xml).find('link').each(function() {
                    $('#download').append('
track
');
                    });
                }
            });
        }
</script>

Thanks again.


text:
Q: TabControl ItemTemplate with UserControl inside I have a question about using TabControl with mvvm pattern.
Here is some parts of my code:
<UserControl>
        <UserControl.DataContext>
            <vm:TabsViewModel />
        </UserControl.DataContext>
        <UserControl.Resources>
            <ResourceDictionary >
                <ResourceDictionary.MergedDictionaries>
                    <ResourceDictionary Source="../Styles/Converters.xaml"/>
                </ResourceDictionary.MergedDictionaries>
            </ResourceDictionary>
        </UserControl.Resources>

        <Grid>
            <Grid.Resources>
                <Style x:Key="TabItemStyle" TargetType="TabItem">
                    <Setter Property="Header" Value="{Binding Customer.LastName}"/>
                    <Setter Property="Content" Value="{Binding}"/>
                </Style>
                <DataTemplate x:Key="TabItemHeaderTemplate">
                    <TextBlock Text="{Binding}" FontWeight="Medium"/>
                </DataTemplate>
                <DataTemplate x:Key="TabItemContentTemplate" x:Shared="false">
                    <Grid>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition />
                            <ColumnDefinition />
                        </Grid.ColumnDefinitions>

                        <GroupBox Header="Info">
                            <StackPanel Orientation="Horizontal" Grid.Column="0">
                                <TextBlock Text="{Binding Customer.FullName}" />
                            </StackPanel>
                        </GroupBox>

                        <GroupBox Header="Finances" Grid.Column="1" >
                            <controls:CustomerFinancesView DataContextChanged="CustomerFinancesView_DataContextChanged">
<controls:CustomerFinancesView.DataContext>
<vm:FinancesViewModel />
</controls:CustomerFinancesView.DataContext>
                            </controls:CustomerFinancesView>
                        </GroupBox>
                    </Grid>
                </DataTemplate>
            </Grid.Resources>
            <TabControl
                ItemsSource="{Binding Tabs, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
                SelectedItem="{Binding CurrentTab, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
                ItemContainerStyle="{StaticResource TabItemStyle}"
                ItemTemplate="{StaticResource TabItemHeaderTemplate}"
                ContentTemplate="{StaticResource TabItemContentTemplate}"/>
        </Grid>
    </UserControl>

Underlaying view model provide methods and commands to add or remove tabs. Like so:
public class TabsViewModel : InteractableModel
{
    ObservableCollection<TabModel> _tabs = new ObservableCollection<TabModel>();
    public ObservableCollection<TabModel> Tabs
    {
        get
        {
            return _tabs;
        }
        set
        {
            if (_tabs == value)
                return;

            _tabs = value;
            OnPropertyChanged("Tabs");
        }
    }

    private TabModel _currentTab;
    public TabModel CurrentTab
    {
        get { return _currentTab; }
        set
        {
            if (_currentTab == value)
                return;

            _currentTab = value;
            OnPropertyChanged("CurrentTab");
        }
    }

    public TabsViewModel()
    {
        ...
    }

    void OpenTab(Customer customer)
    {
      var existedTab = Tabs.FirstOrDefault(t=>t.Customer.ID == customer.ID);
      if (existedTab != null)
      {
        existedTab.Refresh();
        CurrentTab = existedTab;
      }
      else
      {
    var newTab = new TabModel(customer);

    Tabs.Add(newTab);

    CurrentTab = newTab;
      }
    }

    void RemoveTab(object param)
    {
       var tabToRemove = Tabs.ElementAtOrDefault((int)param);

       if (tabToRemove != null)
       {
          Tabs.Remove(tabToRemove);
       }
    }

}

}
As you can see, content of each TabItem templated by TabItemContentTemplate DataTemplate. This DataTemplate contains UserControl inside. Assume that this is just empty usercontrol from VS template.
When i'm open first tab - this control ctor is called, corresponding viewmodel creates, and DataContextChanged event is raised. But opening any other tab, or reopening this one doesn't affect on creating this UserControl - it's still those control instance that was created for the first tab opening. Same thing with viewmodel (ctor not called) and event (not raising).
Please help me to find out a way to instantiate this user control from datatemplate every time i'm open tab (OR every time i'm open NEW tab; both variants suits) and destroy it every time i'm closing tab. I've read a lot articles about this, but only thing i found is to use
x:Shared=false

on DataTemplate. But this workaround isn't working for me.
P.S. My final goal is to provide Tab-specific data to DataTemplate's inner UserControl using mvvm pattern. (every tab stores a lot information inside. This information is separated into usercontrols with it's own view model. I want to customize displaying data for each tab controls by binding it to current tab model. Like so: TabsViewModel stores Collection; TabModel stores Model, Control1VM(Model), Control2VM(Model), ...)


text:
Q: I am trying to run XGBoost in R but am facing some issues I have a dataset of 25 variables and 248 rows.
There are 8-factor variables and the rest are integers and numbers.
I am trying to run XGBoost.
I have done the following code: -
# Partition Data
     set.seed(1234)
     ind <- sample(2, nrow(mission), replace = T, prob = c(0.7,0.3))
     train <- mission[ind == 1,]
     test <- mission[ind == 2,]

   # Create matrix - One-Hot Encoding for Factor variables
     trainm <- sparse.model.matrix(GRL ~ .-1, data = train)
     head(trainm)
     train_label <- train[,"GRL"]
     train_matrix <- xgb.DMatrix(data = as.matrix(trainm), label = train_label)

     testm <- sparse.model.matrix(GRL~.-1, data = test)
     test_label <- test[,"GRL"]
     test_matrix <- xgb.DMatrix(data = as.matrix(testm),label = test_label)

The response variable here is "GRL" and I am running the test_label <- test[,"GRL"]
The above code is getting executed but when I am trying to use it in xgb.DMatrix, I am encountering the following error:

Error in setinfo.xgb.DMatrix(dmat, names(p), p[[1]]) :
The length of labels must equal to the number of rows in the input data

I have partitioned the data into 70:30.

A: test[,"GRL"] returns a data.frame, and XGBoost needs the label to be a vector.
Just use teste$GRL or test[["GRL"]] instead. You also need to do the same for the training dataset


text:
Q: FB.init called with one app, but I want to switch to another Facebook app I have the main FB.init being called on all of my pages, but there are certain sections of the site where I'd like to get the user's permissions for a different app.
Is this possible? I don't think I can do another FB.init, but I'm wondering if I can specify a different app for a different task.

A: I can't think of why you'd want to do this; but can't you just store the [Facebook] access token for the two apps in your app's own session?


text:
Q: How to write Climpact compatible netCDF file in R? I am a beginner with Spatio-temporal data in R. I have daily precipitation data in .tif format and I created netCDF file to use as input to Climpact. But I get an error when I use this data as input to Climpact.
Fehler in create.file.metadata(f, variable.name.map) :
  !is.null(projection) ist nicht TRUE
Ruft auf: create.indices.from.files -> create.file.metadata -> stopifnot
Ausführung angehalten

I assume that the issue is with the CRS system. How can I write the data in netCDF format in R which will be compatible with Climpact?
My code to write necDCF file was
library(raster)

raster_paths <- "/Users/dipesh/Desktop/demo/data"
raster_paths <- list.files(raster_paths, full.names = TRUE) # only one year sample

ptot_data<- lapply(raster_paths, brick)
ptot_data<- stack(ptot_data)

ptot_data <- projectRaster(from=ptot_data, crs="EPSG:4326")

dates_obs<- hydroTSM::dip("2020-01-01", "2020-12-31")
ptot_data<- setZ(ptot_data, dates_obs, name='time')

if(require(ncdf4)){
  writeRaster(ptot_data, "DC/daily_ppt_npl_2020.nc", overwrite=TRUE, format="CDF", varname="ppt", varunit="kg m-2 d-1",
              longname="Total Daily Precipitation", xname="Longitude",   yname="Latitude", zname="time", zunit = "day")

}

I want to organize my data similar to this sample
https://github.com/ARCCSS-extremes/climpact/blob/master/www/sample_data/climpact.sampledata.gridded.1991-2010.nc
Looking for your support.
Revision:
I guess I lost the CRS information while writing the netCDF in R so I added it back using gdal_translate. I also edited variable attributes using NCO ncatted and the data is now CF-Compliance compatible. My initial error is now gone but I got another error.
'''Creating cluster of 3 nodes of type SOCK
proj_create: Error 1027 (Invalid value for an argument): pj_init_ctx: Must specify ellipsoid or sphere''''

Is this error familiar to you?


text:
Q: SurfaceView not showing up I have a class which is called when I press a button, the .xml file used as the background is just a black screen.  When I run my application I am getting this error:
FATAL EXCEPTION: main
java.lang.NullPointerException
  at com.synlight_development.tattoo_it.Menu$2.onClick(Menu.java:71)
  at android.view.View.performClick(View.java:2532)
  at android.view.View$PerformClick.run(View.java:9293)
  at android.os.Handler.handleCallback(Handler.java:587)
  at android.os.Handler.dispatchMessage(Handler.java:92)
  at android.os.Looper.loop(Looper.java:150)
  at android.app.ActivityThread.main(ActivityThread.java:4263)
  at java.lang.reflect.Method.invokeNative(Native Method)
  at java.lang.reflect.Method.invoke(Method.java:507)
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
  at dalvik.system.NativeStart.main(Native Method)

A: because of surfaceView default shown on bottom of window.
try this
   v.setZOrderOnTop(true);  //it puts surfaceview to top of your window.

or also in your SView class set these parameters in constructor etc.
   setZOrderOnTop(true);

If you want to use GlSurfaceView. In constructor try this,
   setEGLConfigChooser(8,8,8,8,16,0);
   getHolder().setFormat(PixelFormat.TRANSLUCENT);

thanks to that your surface view becomes transparent.
if you try put your surfaceView to middlelayer of window it's more harder than this
   surfaceView.setZOrderMediaOverlay(true);

and also you seen black screen because your surfaceview needs another surfaceview to get top of.
I solved this, i create another surfaceView (Maybe you want to use CameraView etc). and drawn
background images, and other surfaceView get top of that, and add another views top of window
like that.
1.Layer -> backgroundDrawnSurfaceView
2.Layer (Middle Layer)->myrealSurfaceView
3.Layer -> Another Views.

A: You edited your problem
firstly you add SView action listener itself.
after that in Editor activity onCreate you add onTouch listener to your SView, Editor.
and not found Thread.
try this solution-> delete
    v.setOnTouchListener(this);

and add
  sleep(50);

in SView, on touch listener.


text:
Q: How to select closest representative to the center in each cluster in scipy-cluster? So basically, I use the Python module scipy-cluster to plot a lot of data points. Is there are way/function that give the representative of each cluster if given the threshold, or the number of representatives I want? Ideally, each representative must has the closest distance to the center of the cluster it belongs to.
Edit: I'm looking for the data point closest to the centroid in each cluster.

A: I don't really know my way around scipy-cluster, but it sounds like it gives you the centroid coordinates. Given that information and the knowledge of which points are in the cluster, it should be trivial to calculate the distance from the centroid for each point in the cluster. Just make sure your calculation is based on the same distance metric you used for clustering (probably euclidean distance).

A: Scipy-cluster provides coordinates for each centroid and identifies which points are in each cluster. Once you have that, I believe scipy.cluster.vq.py_vq will give you the distance between observations and centroids.


text:
Q: Compiler error of "Non-nullable field is uninitialized" even though it was initialized in InitializeComponents function In WinForms it is common that a common initialization function is initializing reference variables (for example)
class SomeClass : Form {
  Button b;

  SomeClass() {
    InitializeComponents();
  }

  SomeClass(Container x) {
    InitializeComponents();
  }

  void InitializeComponents() {
    b = new Button();
  }
}

As you can see b is always initialized to a non-null value. However, C# 8 will still complain that SomeClass() does not initialize non-nullable value b.
Of course I could mark b as nullable (Button? b) however, now I will get a warning on every usage of b, since nullability is not checked (it cannot be null...)
What is the best way to resolve this. Is there an attribute that can be used to flag InitializeComponent as being always called by constructor?
Please note, this is a very common pattern in WinForms (every component...)
Yuval

A: As per the preview docs:

Q: Why are warnings reported for fields that are initialized
  indirectly by the constructor, or outside the constructor?
A: The compiler recognizes fields assigned explicitly in the current
  constructor only, and warns for other fields declared as non-nullable.
  That ignores other ways fields may be initialized such as factory
  methods, helper methods, property setters, and object initializers. We
  will investigate recognizing common initialization patterns to avoid
  unnecessary warnings.

So, there is no way, right now to achieve what you want without moving that assignment directly into the constructor (or assigning it on the line that declares it).

A: For your very specific example the solution is to merge InitializeComponent() into the default constructor and to invoke it from the second one.
class SomeClass : Form {
  private readonly Button b;

  public SomeClass() {
    b = new Button();
  }

  public SomeClass(Container x): this() {
    // Something else...
  }
}

Unfortunately this is a well-known current limitation and, moreover, all the designer generated code won't follow this pattern then you may need to put some #nullable disable (or one of the other directives, as appropriate) here and there.


text:
Q: sending messages to the main window in a thread in win32 I am relatively new to working with threads in Win32 api and have reached a problem that i am unable to work out.
Heres my problem, i have 4 threads (they work as intended) that allow the operator to test 4 terminals. In each thread i am trying to send a message to the main windows form with either Pass or Fail, this is placed within a listbox. Below is one of the threads, the remaining are exactly the same.
void Thread1(PVOID pvoid)
{
for(int i=0;i<numberOfTests1;i++) {
    int ret;
    double TimeOut = 60.0;
    int Lng = 1;
    test1[i].testNumber = getTestNumber(test1[i].testName);
    unsigned char Param[255] = {0};
    unsigned char Port1 = port1;

    ret = PSB30_Open(Port1, 16);
    ret = PSB30_SendOrder (Port1, test1[i].testNumber, &Param[0], &Lng, &TimeOut);
    ret = PSB30_Close (Port1);

    if(*Param == 1) SendDlgItemMessage(hWnd,IDT_RESULTLIST1,LB_ADDSTRING,i,(LPARAM)"PASS");
    else SendDlgItemMessage(hWnd,IDT_RESULTLIST1,LB_ADDSTRING,i,(LPARAM)"FAIL");
}
_endthread();
}

I have debugged the code and it does everything except populate the listbox, i assume because its a thread i am missing something as the same code works outwith the thread. Do i need to put the thread to sleep while it sends the message to the main window?
Any help is appreciated.
Cheers

A: You don't want your secondary threads trying to manipulate your UI elements directly (such as the SendDlgItemMessage). Instead, you normally want to post something like a WM_COMMAND or WM_USER+N to the main window, and let that manipulate the UI elements accordingly.


text:
Q: Enforcing database integrity Would this ever make sense to have application enforce the database integrity instead of having foreign keys, check constraints, etc?
How much of a performance improvement one can expect for not enforcing database integrity through internal database tools?

A: It's common practice to drop constraints (foreign keys, CHECK, etc) and indexes if you're doing a large enough data load, and re-enable/implement the constraints & indexes afterwards.  That validation has a time cost.  That's assuming you can't use database specific bulk load syntax (incl. minimizing logging).
It's impossible to say how much of a performance increase to expect - each situation is unique (data types, design, etc).  The only way to truly know is to test.

A: There are a few times when constraints get in the way:

*

*When you need to use Single Table Inheritance (STI). Imagine you sell to both individuals and organizations. You will need a single "Party" table whose row is either an individual or an org. STI means you need some nullable fields that shouldn't be null. Class Table Inheritance solves this, but this is harder for some ORMs. Ruby's ActiveRecord only supports STI, for example.

*When you need to support Draft versions of an entity, that may not be completely valid. You could store a draft as json, but then it's harder to reuse the same identifier on the client - imagine it's been saved with id=5, edited to be not valid, and autosaved as draftid=99. In this case all of your fields would probably have to be nullable.

A: Truth be told, not only will you not see much performance loss from having foreign key constraints in the database, but you will see performance enhancements. The SQL Server query optimizer is built around the concept of primary and foriegn keys as well as other types of data constraints. If these are in place and enforced the optimizer can take advantage of them to get you better performance. Here's a blog post with a simple example that shows it in action.
If you are in an edge case where you truly have more inserts than reads (and updates & deletes require reads, so they usually end up adding to the read count), then it might make sense to remove constraints from the data for performance, maybe. But since the overwhelming majority of databases are read oriented, you're sacrificing performance, not enhancing it.
And none of this mentions the fact that data integrity is better handled at the database since you only have to create it once where as if you do all the work in code, you may have to do it multiple times for multiple apps (unless you design your data access layer carefully and require every app access the db to go through that same layer).
If you're using a relational database system, I say, why not really use it. If you don't need relational data, go with Hadoop or something else.

A: A lot of application developers think so.
When you're tempted to delegate data integrity to application code, think "Every programmer and every application that hits this database from now until the end of time has to get it perfectly right, every time."
What are the odds?

A: Even if there is any performance gain, it's negligable compared to the return of referential integrity and generalized data integrity.
Long gone are the days where a database is a dumb data store.  Leverage the power that RDBMS' offer.
Performance gains aren't everything, especially on such a small scale as this.  But when you find out you have a supposed foreign key relationship that your application is supposed to enforce, and it turns out that is not a primary key in the referencing table then you'll care very little about performance gain (if any, I can't speak on the specifics of that).


text:
Q: Adding values from a list of queries with a specific "step" I was wondering if there is a way to add values to an array, within a range [x, y] (having a list of queries) with a specific "step", faster than O(queries * (range_length / step)): you should add values like this: for each pos = x + k * step, where k goes from 0 to infinity, pos <= y, array[pos] += value.
I thought about adding the value in another array, like this:
auxarray[x] += value;
auxarray[y + 1] -= value;
for (int i = 1; i <= size; ++i) {
    auxarray[i] += auxarray[i - 1];
    array[i] += auxarray[i];
}

Unfortunately, I don't know what to do with the cells that the value shouldn't be added to.

A: Not sure I got the question right, but if I did why not doing:
curr = x;
while (curr <= y) {
    array[curr] += value;
    curr += step;
}

Regarding the faster than O(queries * range_length), I don't think it is possible, though it is acctually:
O(queries * (range_length / step))


text:
Q: Predecir valores utilizando forecast.Arima y xreg Estoy intentando predecir valores usando forecast.Arima y los argumentos xtreg y h
Mis códigos en R son:
monthlylFatal <- ts(Spainmonthly$fatalities, start=c(1995,1), end=          c(2013,12), frequency=12)
Spainpps <- ts(Spainmonthly$pps.2007, start=c(1995,1), end=c(2013,12), frequency=12)
Spainfinanc.cris <- ts(Spainmonthly$financ.cris.2008, start=c(1995,1), end=c(2013,12), frequency=12)
xreg <- cbind(Spainpps,Spainfinanc.cris)

arima1=Arima(logmonthlylFatal,order=c(0,1,1), seasonal=c(1,1,2), xreg = xreg)
forecast.arima1=forecast.Arima(arima1, xreg = xreg, h=84)
forecast.arima1

Me gustaría predecir valores desde Enero 2014 hasta Diciembre 2020 (h=84), pero como resultado obtengo predicciones hasta más del 2030. Por qué?


text:
Q: laravel basic program not working with routing am trying to develop a web application with the help of LARAVEL framework and am successfully installed the Laravel in my laptop.
I want to make a basic controller and a view program. and routing . is there any error in my program and reply to this question please.
My Controller,view, routes files are described in below
NewController.php

<?php

class New_Controller extends BaseController {

public function action_index()()
{
    return View::make('hai');
}

}

hai.php

Laravel Basics

Jishad is Developing Laravel 4

Routes.php

<?php

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the Closure to execute when that URI is requested.
|
*/

Route::get('/', function()
{
return View::make('hai');
});

A: 1.Your routing is wrong, if you want to point your route to a controller do this:
Route::get('/', 'NewController@action_index');

2.If the name of your controller is NewController then your class should also be that:
class NewController extends BaseController {

  public function action_index()
  {
    return View::make('hai');
  }

}

3.Also the public function action_index()() should be public function action_index().

A: You may try something like following. Declare the route (It'll call index method from NewController when you access home page):
Route::get('/', 'NewController@index');

Now create your NewController like this:
// NewController.php
class NewController extends BaseController {

    // You may keep this line in your BaseController
    // so you don't need to use it in every controller
    protected $layout = 'layouts.master';

    public function index()
    {
        // Make the view and pass a $name variable to the view with
        // Jishad as it's value and then set the $view to the layout
        $view = View::make('hai')->with('name', 'Jishad');
        $this->layout->content = $view;
    }
}

Now Since you are new to this framework so I would suggest to use controller layout instead of blade layout but you may find everything about layout/templating here. To make it working you need to create the master layout in app/views/layouts folder like this:
// app/views/layouts/master.php
<!DOCTYPE html>

        <title>Simple Web Page</title>

<?php echo $content; ?>

Also need to create the hai view in app/views folder like:
// hai.php

Welcome TO Laravel

<?php echo $name ?> is developing learning Laravel

You need to read more about Laravel, check the Laravel - 4 documentation and read some articles/books. Also You used action_index but it was used in Laravel - 3, just use index.


text:
Q: Django: Bad request when sending request using reactJS I am using django-rest-framework at backend and I am trying to post following data from react frontend.
handleSubmit() {
   fetch('http://127.0.0.1:8000/api/debt/create',{
       method: 'POST',
       headers: {
           Authorization: `Bearer ${localStorage.getItem('id_token')}`,
           'Content-Type': 'application/json'
       },
       body: JSON.stringify({
           user: '1',
           customer: '9',
           debtKey: 'b1d9ef1b-45ad-4dc5-80cc-95f7994c0aae',
           createduserKey: '0245abb9-2837-4f37-ae02-9be1b88887ef',
           totalDebt: 789,
           receivedAmount: 115,
           description: 'Debt description',
           paymentDate: '01.01.2019'
       }),
   }).then(response => {
       console.log(response);
       return response.json()
   }).then(json => {
       //this.setState({
       //    user:json
       //});
   });
 console.log("Form Sumbmssion");
}

But I am getting "BAD REQUEST" error. What I am missing? Thanks

A: I think you just need to add "/" to http://127.0.0.1:8000/api/debt/create at the end.
Bad request is often due to that issue only. But why are you using fetch anyway. Please consider using axios if you are using React.js on the frontend. It is identical to fetchAPI, but is lot more flexible.

A: Authorization is a key .it should be in quotes.
headers: {
       'Authorization': `Bearer ${localStorage.getItem('id_token')}`,
       'Content-Type': 'application/json'
   },


text:
Q: Beginner Bluetooth Stack Advice Hay peeps
I'm relatively new to Bluetooth and its inner workings and am trying to still understand some of the concepts and procedures. My question relates to the Bluetooth stack.
I understand there is a Bluetooth stack on the OS side such as Linux Bluez, Windows, Androids Bluedroid etc... but do peripheral devices implement a stack within themselves for example I connect a Bluetooth mouse to a Linux system, Linux of course implements the Bluez stack does the mouse them implement a Bluetooth stack?
I am trying to understand which device will implement security in this situation would it be the Linux with its Bluez or the mouse peripheral.
Thanks

A: Yes, But the difference is that peripheral devices wont support all the profiles and features compared to a Bluetooth stack in OS like Linux or android.
Bluetooth is one of the wireless protocols. Protocol is a procedure or system of rules to follow. So both devices should follow the same protocol for communication. If one of these devices is not following the required protocol, then the other device can't communicate with it. It is like a common language between two people. To follow these protocols all device should have stack. Bluetooth mouse and keyboard also will have Bluetooth stack.
Bluetooth is divided into core protocols and profiles. Core and some profiles are needed for all devices for scanning, pairing etc Example GAP, GATT. Some profile are for a particular use case. For Keyboard and Mouse is is HID profile. For steaming HiFi audio it is A2DP. For voice communication it is HFP. Each peripheral device will implement only the required profiles for their use case because of memory and cost constraints.
The OS will generally implement all the profiles because it needed to connect to most of the peripheral devices. For example A2DP to connect with Bluetooth headset, HID/HOGP to connect with mouse, SPP/OBEX for file transfer over Bluetooth.
Security is implemented in GAP in BREDR and SMP in BLE. These are implemented in all the devices.
Bluetooth stacks are implemented in different ways too. Some places it is entirely implemented in Bluetooth controller(Mostly along with application all in single chip), But in some place it is split between host CPU(In OS) and Bluetooth controller(In firmware). Bludroid and Bluez are the upper part running in the Host CPU(Above HCI). There will be a lower part of the stacks(Above HCI) running in the Bluetooth controller attached to the Device.
The best place to start learning about Bluetooth is Bluetooth SIG website


text:
Q: UICollectionView Memory Leak (with UIWebView or UIImageView inside cells) In my app, I have a UICollectionView with some of cells with images from web and some with Youtube videos via UIWebView. When I press Back via NavigationController memory seems to add up more and more every time. I tried disabling video player, it helped a bit, but still..
CollectionViewController
    var listOfData = [SingleData]()
    var Data:[[String:AnyObject]]?{
            didSet{
                for asset in Data! {
                        let info = SingleData.init(Data: asset)
                        listOfData.append(info)
                 }
            }
        }

    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        listOfData.removeAll()
        Data?.removeAll()
        imageCache.removeAllObjects()
    }

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
            return  listOfData.count
    }

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

            let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Data Single Cell", forIndexPath: indexPath) as! CollectionViewControllerCell
            cell.oneData = listOfData[indexPath.item]
            return cell
    }

CollectionViewControllerCell
    @IBOutlet var videoWebView: UIWebView!
    @IBOutlet var singleDataImageView: UIImageView!

    var oneData:SingleData! {
        didSet{
            updateUI()
        }
    }

    func updateUI(){

        singleImageView.image = nil

        if (oneData.isVideo == true) {
            videoWebView.hidden = false
            singleDataImageView.hidden = true
            showVideo()
        } else {
            videoWebView.hidden = true
            singleDataImageView.hidden = false
            setImage(oneData.imageURL, singleDataImageView)
        }
    }

    func showVideo() {
        if let videoUrl = oneData.videoUrl {

            let replacedString = videoUrl.replace("watch?v=", withString: "embed/")
            videoWebView.scrollView.scrollEnabled = false
            videoWebView.scrollView.bounces = false
            videoWebView.allowsInlineMediaPlayback = true

            let embededHTML = "<title>.</title>"

            videoWebView.loadHTMLString(embededHTML, baseURL:nil)

        }

    }

    func setImage(url : String?, _ imageView : UIImageView) {

        imageView.image = nil
        imageUrlString = url

        if let cUrl = url {

            if let imageFromCache = imageCache.objectForKey(cUrl) as? UIImage {
                imageView.image = imageFromCache
                return
            }

            if let urlImage = NSURL(string: cUrl) {

                Request.sharedInstance.session.dataTaskWithURL(urlImage, completionHandler: { (data, response, error) in
                    if error != nil {
                        print(error)
                        return
                    }

                    dispatch_async(dispatch_get_main_queue(), {

                        let imageToCache = UIImage(data: data!)

                        if self.imageUrlString == url {
                            imageView.image = imageToCache
                        }

                        imageCache.setObject(imageToCache!, forKey: url!)
                    });

                }).resume()
            }
        }

    }

SingleData
class SingleData {

    var imageURL:String? = nil
    var videoUrl:String? = nil
    var isVideo:Bool? = false
    var dataAssets:Dictionary<String, AnyObject>?

    init(Data : Dictionary<String, AnyObject>?){
        dataAssets = Data
        if Data!["MediaContent"]!["MediaType"] as? Int == 2 {
            isVideo = true
        }

        imageURL = dataAssets!["MediaContent"]!["FileUrl"] as? String
        videoUrl = dataAssets!["MediaContent"]!["FileName"] as? String
    }

}


text:
Q: How can I extract a 2D array that is stored in a JSON file? I have the following code that I am using to open the above json file and extract the data. However, I only want the coordinate data, but the code gives me the following error.
TypeError: string indices must be integers.
How would I print out just the coordinates data?
{
"type": "Polygon",
"coordinates": [
    [
        [
            -5.84731,
            60.5832
        ],
        [
            -5.93843,
            60.5832
        ],
        [
            -2.39097,
            60.5832
        ],
        [
            -2.39097,
            60.5843
        ],
        [
            -2.75097,
            60.5823
        ]
    ]
]
}

import json

f = open('allData.json')
data = json.load(f)
print(data['type']['coordinate'])

f.close()

A: print(data['type']['coordinate'])

This is fetching data['type'] first, = "Polygon", and then applying index ['coordinate'] to that, hence the error you're getting about indexing a string.
coordinates (plural) is not a child of type in your structure. You want data['coordinates'].

A: You just need to call the coordinates
import json

f = open('allData.json')
data = json.load(f)
print(data['coordinates'])
f.close()

Output
[[[-5.84731, 60.5832], [-5.93843, 60.5832], [-2.39097, 60.5832], [-2.39097, 60.5843], [-2.75097, 60.5823]]]


text:
Q: OpenPGP C++: cmake - library not found for -lgmpxx Context
I am trying to use the OpenPGP C++ library on a MacOS machine.
Issue
I am following the instruction to build the library:
mkdir build
cd build
cmake ..
make
<make test>
make install

I manage to run the cmake. When passing to the step of make it returns an error:
[...]
[ 54%] Linking CXX shared library libOpenPGP.dylib
ld: library not found for -lgmpxx
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make[2]: *** [libOpenPGP.dylib] Error 1
make[1]: *** [CMakeFiles/OpenPGP_shared.dir/all] Error 2
make: *** [all] Error 2

What I tried
After reading online I found that could have been an issue of not properly run the cmake command.

*

*I re-runned the cmake command (deleting the build folder content first)

*I re-cloned the repository


text:
Q: expressJS - path values in App.use to mount a Middleware I'm confused about path in express.use.
In express document https://expressjs.com/en/4x/api.html#app.use
it said: Path:This will match paths starting with /abcd:
app.use('/abcd', function (req, res, next) {
next()

})
Does this mean the '/abcd' in app.use work like regex?, which will match any url starting with /abcd (like /abcd/efg)
Then, it will somehow "remove" the /abcd part in the above url, and pass "/efg" to the middleware function?
(by middleware, I am referring to the router example here app.use('/birds', birds)
https://expressjs.com/en/guide/routing.html)
If so, is express.router.use(), router.get(), App.get() works the same way?


text:
Q: Store an operator in a variable with Ruby Ruby has such beautiful syntactic sugar that I was sure this would work:
f = :+
g = 1 f 2 // => 3

But, of course, it doesn't.
Is there something similar?  Obviously there are many easy ways around needing to do this, but does Ruby's commitment to amazing sugar extend to doing something like this?

A: Yeah, you can do so with Object#public_send method:
f = :+
puts 1.public_send(f, 2) # => 3

From docs:

Invokes the method identified by symbol, passing it any arguments specified. Unlike #send, #public_send calls public methods only.


text:
Q: How can I create an Lambda Expression for Linq in the Where clause for two tables after the Join? I have this,
 Expression<Func<MyCourse, bool>> filter = mc => mc.Active == 1;
 Func<MyCourse, bool> funcWhere = filter.Compile();

and then this,
var myClasses = db.MyCourse.Join(db.People, mc => mc.PersonId,
p => p.PersonId, (mc, p) => new { MyCourse= mc, Person = p }).Where(???)

The reason I need to do it this way is because if I put the filter on the MyCourse table first with,
db.MyCourse.Where(funcWhere).Join....

The SQL created brings back all of the People and all of the MyCourse and then uses the filter.  If I do the where at the end,
(mc, p) => new { MyCourse= mc, Person = p }).Where(mc=>mc.MyCourse.Active == 1)

I get a good query with the Joins.  Else the engine queries all the rows into memory first.  Two separate queries with thousands of rows.
I have seen a tremendous amount of questions on SO and elsewhere about this.  I cannot find one that tells me how to do the Expression when there is more than one table, from a Join, using a dynamic Where Expression<Func<T,TResult>>.
The goal is to make a dynamic query statement based upon Expressions (not Dynamic Linq, and no third party.)  In fact, this question claims the Where at the end is slower, but in my program it does the correct query with Joins.
MyCourse has a PersonId and People has a PersonId.  If I wrote this by hand it'd look like,
select mc.CourseName, p.LastName
from MyCourse mc inner join Person p on mc.PersonId = p.PersonId
where mc.Active = 1;

(Those are just example columns for the question.  They're not really what I want from the above query, except Active == 1.)
Where clause with Join in lambda expression
Update:  FWIW, I was able to get it working this this,
    var param = Expression.Parameter(typeof(MyClass), "MyClassDebug");
    var exp = Expression.Lambda<Func<MyClass, bool>>(
        Expression.Equal(
            Expression.Property(param, dbParameter),
            Expression.Constant(dbValue)
        ),
        param
    );

I did not do navigation properties or anything else.  And I was able to use it like this,
var MyQuery = (from recs in dbcontext.MyClass.Where(exp)
               ...three joins

The produced SQL looked good, and the Explain plan showed minimal row retrieval.

A: I suspect calling Compile() on your Expression is causing your trouble. Your full query includes the Join, but you've already compiled the Where clause, so it can't compile the entire query including the Join together. That might be why it's grabbing the entire table because it's executing the Where by itself first, then doing the Join later.
But you don't need to call Compile(). Just pass the Expression into Where():
Expression<Func<MyCourse, bool>> filter = mc => mc.Active == 1;
var myClasses = db.MyCourse
    .Where(filter)
    .Join(db.People, mc => mc.PersonId,
p => p.PersonId, (mc, p) => new { MyCourse= mc, Person = p }).ToList();

Somewhat unrelated to your actual problem, but if you created the foreign keys, you can simplify this a bit. Update your model in your Visual Studio project if you haven't already. Your Person class will change to have a list of MyCourse and your MyCourse class will have a list of Person.
So you can do something like:
Expression<Func<MyCourse, bool>> filter = mc => mc.Active == 1;
var courses = db.MyCourse.Include("Person").Where(filter);
foreach (var course in courses) {
    var person = course.Person; //This is populated with the Person record
}

Linq handles the join, and each MyCourse returned will have a Person property.


text:
Q: ng-model not updating md-slider with md-discrete directive

var app = angular.module('StarterApp', ['ngMaterial']);
.overflow-hidden{
  overflow: hidden;
}

md-slider:not(.active) .md-thumb-container{
      transition: transform .4s cubic-bezier(.25,.8,.25,1)!important;
}

md-slider:not(.active) .md-track-fill{
  transition: width .4s cubic-bezier(.25,.8,.25,1)!important;
}

    <link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/angular_material/0.7.1/angular-material.min.css">

  <md-content class="md-padding overflow-hidden">

Demo

      <md-slider flex md-discrete step="1" min="1" max="25" aria-label="rating" ng-model="value">
      </md-slider>

Value = {{value}}

  </md-content>

while sliding ng-model value is not updating in md-slider when I am using md-discrete directive, without that its working fine. How I can able to get that work with md-discrete ?

A: The whole point of using md-discrete is to updated the ng-model only on the drag end, because sometimes we run a bulky function (time consuming!) and it will run for each change of the slider's ng-model, so by using md-discrete, the default functionality is to update after the drag-end. My suggestion is to use the md-slider without md-discrete if you don't want this behavior.

var app = angular.module('StarterApp', ['ngMaterial']);
.overflow-hidden{
  overflow: hidden;
}

md-slider:not(.active) .md-thumb-container{
      transition: transform .4s cubic-bezier(.25,.8,.25,1)!important;
}

md-slider:not(.active) .md-track-fill{
  transition: width .4s cubic-bezier(.25,.8,.25,1)!important;
}

    <link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/angular_material/0.7.1/angular-material.min.css">

  <md-content class="md-padding overflow-hidden">

Demo

      <md-slider flex step="1" min="1" max="25" aria-label="rating" ng-model="value">
      </md-slider>

Value = {{value}}

  </md-content>


text:
Q: Chrome Extension "Stats" broken since update? I recently updated a Chrome extension I have, and since the update my Stats has shown 0s for both views and installs. Here's what the chart looks like:

Any idea why this might be happening? From an Incognito window I can still find my extension in the Chrome store.
For those curious, the extension is called "Prioritab"

A: Did you by any chance change the Extension name with the update? I'm noticing the same behaviour with my app and I changed the app name with the latest update.
Can't think of what else might have caused it...


text:
Q: how to create new module in Laravel Is there any simple way to create new module in Laravel, if yes then please explain in detail.
Need to create new custom module in Laravel for users, product etc but didnt understand how to proceed with the same.

A: These packages will not help you if you don't understanding what exactly are you doing. I really recommend you to start with this tutorial, for example.

A: You should be right to go with
php artisan module:make <module_name>

You can also create multiple modules at once doing this:
php artisan module:make Users Products

this command will create all the resources you need like controller, seed class service provider and scaffold all the routes. If you dont want all this create new module with the following command
php artisan module:make Products --plain

A: After research found solution on GITHub :
https://github.com/jaiwalker/setup-laravel5-package
This might be better way to create a new package.
If anybody have better solution, then please share.

A: To install through Composer, by run the following command:
composer require nwidart/laravel-modules

The package will automatically register a service provider and alias.
Optionally, publish the package's configuration file by running:
php artisan vendor:publish --provider="Nwidart\Modules\LaravelModulesServiceProvider"

By default the module classes are not loaded automatically. You can autoload your modules using psr-4 (composer.json). For example :
{
  "autoload": {
    "psr-4": {
      "App\\": "app/",
      "Modules\\": "Modules/"
    }
  }
}

Creating a module is simple and straightforward. Run the following command to create a module.
php artisan module:make <module-name>

It is also possible to create multiple modules in one command.
php artisan module:make Blog User Auth

A: You can refer this open source project to create module https://asgardcms.com/ - A modular multilingual CMS built with Laravel 5.


text:
Q: Webstorm: Move Line Up or Down Using Webstorm8, I have been unable to figure out when using move line up or down, it will not place the line inside of a function, rather it skips the function either placing the movable line at the top or bottom of the function based on direction of line movement. Any ideas how to move a line up or down a line number as happens in Sublime?

A: Just to clarify if anyone else runs into this... The shortcut of alt up/down is set to 'move statement' by default.
goto File > Settings...
Type Keymap in the lefthand search to find the left nav option of 'keymap'
then in the right hand search search 'move line' and scroll down to switch it as shown in the picture below...

A: Please can you provide a code snippet and exact steps to recreate the issue? Are you sure that you are using Code/Move Line (up/down) and not Code/Move Statement(up/down)?

A: On mac
For line up cmd+Shift+up
For line down cmd+Shift+down

A: From MacbookPro

(sitting->Keymap->MainMenu->code (Move Line Down & up ))

you can change it or see how it works.


text:
Q: Creating a search in php - typing in a city and getting the attractions for that city listed below I have created a database in phpMyAdmin. I want to create a search so it will display tourist attractions. So for example if I type in London the Big Ben will appear, as well as a number of other tourist attractions in London. I want to be able to type in a city and then tourist attractions for that city will appear below.
All the search tutorials I have looked at only retrieve data from one table, and I am retrieving it from two.
I have a table called city, and in that table there is city_id and city_name
I have a second table called attractions and in that table there is city_id, tourist_id, attraction_name, latitude, longitude and cost.
I would like to be able to create a search so when I type in the city_name the  attraction_name, latitude, longitude and cost appears. However I don't know how to link these two tables together in the mysql_query. If anyone could help me that would be really great. Thanks
<?php
require_once('config1.php');
$output = '';
if(isset($_POST['search'])){
$searchq = $_POST['search'];

$query = mysql_query("SELECT * FROM zz_attractions INNER JOIN city on zz_attractions.city_id = zz_city.city_id where zz_city.city_name = ? LIKE '%searchq%'") or die("could not search");
$count = mysql_num_rows ($query);
if ($count == 0) {
    $output = 'there was no search results';
} else {
    while $row = mysql_fetch_array($query)) {
    $attraction_name = $row['attractionname'];
    $lat = $row['latitude'];
    $long = $row['longitude'];
    $cost = $row['cost'];

    $output .= '
'.$attraction_name.' '.lat'. '.long.' '.cost.'
';

    }
?>

A: What you want to use is a "join" query. That looks a little something like this
SELECT * FROM table1 INNER JOIN table2 ON table1.id = table2.id;

In your case that query might look like
SELECT * FROM attractions INNER JOIN city on attractions.city_id = city.city_id where city.city_name = ?

A: You need to make a link between the two tables, using an unique value which is present in both: extra, we have city_id !
So, what you have to do know, is get the values you want using this id.
You have the name of a city, linked to an unique id, and this id brings you to a list of tourist attractions.
You have to make two SQL resquests:
- Get the city_id depending on city_name
- Get the data using this city_id
One solution is to use subquery :
SELECT attraction_name, latitude, longitude, cost FROM attractions WHERE city_id IN (SELECT city_id FROM city WHERE city_name ILIKE 'London');

A: There're more ways how to implement your search. Really easy example for start is to use some autoComplete. You can use Bootstrap TypeAhead or as in and example jQuery EasyAutocomplete.
var options = {
    url: function(phrase) {
        return "http://yourSearchUrl.com/search/?query=" + phrase;
        },
        list: {
            onChooseEvent: function() {
                var item = $(".autocomplete").getSelectedItemData();
                //fill your additional search form with ID for submit
                //$("#input-qId").val(item.id);
                //or redirect to page with attraction
                window.location.href = "http://yourPage.com/attraction/?id=" + item.id;
            }
        },
        template: {
            type: "custom",
            method: function(value, item) {
                //custom template for autocomplete container
                return "" + item.value + "";
            }
        },
        getValue: "value" //defines array index with value
    };

//your input selector
$(".autocomplete").easyAutocomplete(options);

For your search page you can return JSON array from select then. Two possible scenarios for search. When user type "Lo" you can show list of cities.
SELECT city_id, city_name FROM city WHERE city_name LIKE %get_url_phrase%;

Second scenario you search after submitting full city name. Also can return result by just partial city name.
SELECT * FROM attractions WHERE city_id IN (SELECT city_id FROM city WHERE city_name LIKE %get_url_phrase%);

If you search first just for city, then you can pass city_id to attraction search page and perform query
SELECT * FROM attractions WHERE city_id = "cityIdParam"

Possible to match sql query on exact phrase match, city_name = "London", fulltext search, in second query use table JOIN. Like clause just for example, not good performance at all.
The result JSON would be in form like:
[{"id": 1, "value": "AttractionName"}]

If you provide me with more accurate info about implementation i can answer you more :)


text:
Q: Use Windows share with "remote-to-remote" links in Linux I mount a Windows share on recent Linux with default options that work.
But on the Windows share a new symbolic link with the name "archive" has been created that point to another Windows share (on server2). This kinks of links seems to be called "remote-to-remote" symbolic links. Normal "local" links work on the mounted share on the Linux side. Windows clients support that after enabling these kind of links via https://helpcenter.netwrix.com/NA/996/Configure_IT_Infrastructure/File_Servers/Enable_Symlink.html
On Linux this link "archive" looks like this:
archive -> '/??/UNC/server2/folder'
So it seems that the Linux does not understand this kind of link. It could use the same credentials since I can mount "//server2/folder" manually but I need it in the "archive" folder/link.
I already tried the "mfsymlinks" option in the /etc/fstab line with no success.
If I try to mount the //server2/folder over "archive" I get the error: archive: No such file or directory

A: Linux can't easily handle such links client-side because it does not have a fixed path for SMB shares. Your symlinks work on Windows clients because \\<server>\<share> is automatically understood on any Windows client without any custom configuration, but that does not apply to Linux where each share is manually mounted on an arbitrary, user-chosen path.
Now Linux does understand the symlinks, in that it shows you exactly where their target goes (Windows symlinks use NT paths under the hood so \??\UNC\<server> is actually correct), it's simply that there's no automation on Linux to mount SMB shares at the target paths. Even if the target had been translated to //<server> it wouldn't have helped here.
That being said, /??/UNC is a perfectly valid (if weird) Linux path, so you can use the lack of \\ translation to your advantage: you can literally mkdir -p "/??/UNC/server2/folder" and configure your /etc/fstab to mount the other share there. (The question marks aren't a problem.)
In fact you could even configure the autofs service to have a special autofs map at /??/UNC which automatically mounts SMB shares, similar to how autofs would typically be used with NFS.)
But I would instead suggest a different approach: rather than symlinks, use the DFS feature found in SMB. (Not DFS-R, just regular DFS.) Unlike symlinks, DFS referrals are followed by the SMB client rather than being exposed to the filesystem – there is no "symlink path" to be shown to the user. This means the client can mount the target share directly on top of the DFS junction, which allows both Windows and Linux clients to follow DFS referrals without any special configuration.
(You can create "server-hosted DFS namespaces" on any Windows Server machine, including converting an existing share to a DFS namespace. You can also use DFS with Samba, but with a bit more effort.)


text:
Q: Difference between git-lfs env Endpoint and LfsStorageDir? I think I get the mechanics of lfs and its method of tracking the binary files via pointers and only cloning data as needed but I cannot get a solid confirmation where lfs is storing the bulk data. In my case I suspect lfs is keeping the data local because my github repository is tiny (175KB!) relative to the project (Source+Config:72KB, Content:140.7MB) and the local .git directory is much larger (1.2GB).
When I run git lfs env I get the following (left out the bulk of the report, showing what seems related):
Endpoint (s05_testinggrounds_remote)=https://github.com/rebusb/S05_TestingGrounds.git/info/lfs (auth=basic)
...
LocalMediaDir=D:\Unreal Projects\Udemy C++ S05\TestingGRounds\..git\lfs\objects
...
LfsStorageDir=D:\Unreal Proejcts\Udemy C++ S05\TestingGrounds\.git\lfs
...

My intuition says the files are local, the reported size from github is correct,  and not to worry, but it contradicts what I have read about github lfs here, and git-lfs files here. Everything I read says it stores them on a peer or a different server, but how do you identify that server location? I read that the Endpoint reported in the env command should be the location but then the reported size on github is wrong.
Can someone clear up the difference between Endpoint and the LfsStorageDir or explain how to find the actual server/location of the lfs data?

A: Git LFS will, by default, only download the data that you need in order to check out a commit. When it does download data, it downloads it from the location you see in Endpoint to a subdirectory of the LfsStorageDir. New objects you create are also stored in that same subdirectory of LfsStorageDir until you push them.
By default, the origin remote is used, which is labeled as Endpoint=; other remote values are only used if you specify git lfs fetch <remote>. When you push to a remote, the pre-push hooks pushes the relevant LFS data to that remote, using the Endpoint location for that remote. If you want to push all the LFS data, you can use git lfs push --all <remote>.
Many hosting providers (like GitHub) provide a separate large file storage area for your data that is accessible using the standard Git LFS client. It isn't possible to see the files directly on the server, since they are only accessible using the web interface or via the LFS client.


text:
Q: WebAPI: How can I make sure a controller will implement POST? I am working on a WebApi service where I want to create different types of controllers. If a controller should implememt a POST method, then I want to have an interface IPostController that enforces it. However, what if my controller method needs to take a [FromBody] attribute of a specific type? How should my interface look for those [FromBody] methods?
I did create a method in my interface looking like this, but the idea that it enforces an implementation with an object type parameter makes me sceptical.
IHttpActionResult Post([FromBody] object item);

This forces an implementation that looks like the following line:
public IHttpActionResult Post([FromBody]object item){ ... }

If I change the object to the class I actually want to use, I do not implement the interface method anymore.
Any ideas on what should be best practice here?


text:
Q: Tag an already tokenised string with spaCy To make a comparable study, I am working with data that has already been tokenised (not with spacy). I need to use these tokens as input to ensure that I work with the same data across the board. I wish to feed these tokens into spaCy's tagger, but the following fails:
import spacy

nlp = spacy.load('en', disable=['tokenizer', 'parser', 'ner', 'textcat'])
sent = ['I', 'like', 'yellow', 'bananas']

doc = nlp(sent)

for i in doc:
    print(i)

with the following trace
Traceback (most recent call last):
  File "C:/Users/bmvroy/.PyCharm2018.2/config/scratches/scratch_6.py", line 6, in <module>
    doc = nlp(sent)
  File "C:\Users\bmvroy\venv\lib\site-packages\spacy\language.py", line 346, in __call__
    doc = self.make_doc(text)
  File "C:\Users\bmvroy\venv\lib\site-packages\spacy\language.py", line 378, in make_doc
    return self.tokenizer(text)
TypeError: Argument 'string' has incorrect type (expected str, got list)

First of all, I'm not sure why spaCy tries to tokenize the input as I disabled the tokenizer in the load() statement. Second, evidently this is not the way to go.
I am looking for a way to feed the tagger a list of tokens. Is that possible with spaCy?

I tried the solution provided by @aab combined with info from the documentation but to no avail:
from spacy.tokens import Doc
from spacy.lang.en import English
from spacy.pipeline import Tagger

nlp = English()
tagger = Tagger(nlp.vocab)

words = ['Listen', 'up', '.']
spaces = [True, False, False]

doc = Doc(nlp.vocab, words=words, spaces=spaces)
processed = tagger(doc)
print(processed)

This code didn't run, and gave the following error:
    processed = tagger(doc)
  File "pipeline.pyx", line 426, in spacy.pipeline.Tagger.__call__
  File "pipeline.pyx", line 438, in spacy.pipeline.Tagger.predict
AttributeError: 'bool' object has no attribute 'tok2vec'

A: You need to use the alternate way of constructing a document directly using the Doc class. Here's the example from their docs (https://spacy.io/api/doc):
from spacy.tokens import Doc
doc = Doc(nlp.vocab, words=[u'hello', u'world', u'!'], spaces=[True, False, False])

The spaces argument (whether each token is followed by a space) is optional.
Then you can run the components you need, so the whole thing would look like:
import spacy
from spacy.tokens import Doc

nlp = spacy.load('en')
doc = Doc(nlp.vocab, words=[u'hello', u'world', u'!'], spaces=[True, False, False])

nlp.tagger(doc)
nlp.parser(doc)

for t in doc:
    print(t.text, t.pos_, t.tag_, t.dep_, t.head)


text:
Q: Python 3.5 TypeError: a bytes-like object is required, not 'str' using truncate filter I am trying to convert my Python Flask app from 2.7 to 3.5.  I have a simple CMS system using SQLAlchemy where my pages are displayed on the Index page with title and content (which are truncated). That is where my issue is happening.
It returns my pages as a list and my content as a string.  I tried to encode the "pages" but that returns another error because that is not allowed on a list object.
Error:
  File "C:\Python35\lib\site-packages\jinja2\filters.py", line 481, in do_truncate
    result = s[:length - len(end)].rsplit(' ', 1)[0]
TypeError: a bytes-like object is required, not 'str'

The route:
@app.route("/")
def main():
    pages = db.session.query(Pages).all()
    return render_template('index.html', title='Dashboard', pages=pages)

index.html page
{% for page in pages %}

{{ page.title|truncate(150) }}

{{ page.content|truncate(450)|striptags }}

{% endfor %}

A: The error is caused by page.title being a bytes object. You can't use bytes.rsplit() with a str value (which is what truncate does). The truncate filter only supports str Unicode values.
You'll have to make sure pages.title is a unicode str object instead. Do so either by decoding in the template, or by defining the title field to be a Unicode string rather than bytes in your model and database.
Decoding in the template can be done with:
{{ page.title.decode('utf8')|truncate(150) }}

provided your data is actually UTF-8 encoded.
This wasn't an issue in Python 2 as there bytestrings are silently converted to unicode strings as needed (and provided they can be decoded).


text:
Q: Trouble with a simple GetElementById thing real simple Real simple but I'm starting with javascript so it should be quickly soved
I have this html:

and i want to select the div with an id of "logo" with javascript to then overwrite the  with the apropriate file ( a simple browser test to see if you can support SVG )
this innerHTML look like this:
document.getElementById('logo').innerHTML='<content to be added>';

Firebug send me this error: TypeError: document.getElementById("logo") is null
but its right there!
Thanks
okay so here is the full HTML:

    <META CHARSET="UTF-8">
    <title>Bienvenu au Fin Palais</title>

and here's the full svg_support.js I've made;
function getSvgSupport(file)
            {

                var ua = navigator.userAgent;
        if( ua.indexOf("Android") >= 0 )
            {
          var androidversion = parseFloat(ua.slice(ua.indexOf("Android")+8));
          if (androidversion <= 2.3)
                {
                document.getElementById('logo').innerHTML='';

                }

            } else {
                document.getElementById('logo').innerHTML='<embed src="',file,'.svg" type="image/svg+xml" />';
            }
        }

A: yes that is the only reason, and since you seem new to javascript I guess this would make more sense to you
window.onload=function(){
document.getElementById('logo').innerHTML='<content to be added>';
}

You see when your script runs you page has not loaded. so you must use window.onload.
Or you can use this too, if your code is in file.js:

this makes sure your code doesn't run unless document is parsed.

A: You may be trying to run the javascript before the DOM has finished loading. Try this:
$(document).ready(function(){document.getElementById('logo').innerHTML='<content to be added>';});

This assumes you've included jQuery.
As @Thristhart said, you can also use window.onload. This is a built-in javascript event which happens AFTER $(document).ready() does, so you should be safe with that as well.

A: If using JQuery:
$(document).ready(function(){
    $('div#logo').html('<content to be added>');
});

Or
$(function(){
    $('div#logo').html('<content to be added>');
});

A: You don't have to load jQuery if you don't want to it seems like something is off with the chaining of the javascript.  When I broke it apart it worked fine.
Fiddle:  http://jsfiddle.net/DamianHall/GxghG/
var ele = document.getElementById('logo');

ele.innerHTML = 'content to be added';

Looking at other posts it is an onload issue.  The JS fiddle did the onload for me so I didn't notice.


text:
Q: How cast value as tuple (string, bool) It is possible to cast as tuple in this way?
(string value, bool flag) value1 = MethodInfo.Invoke(this, param) as (string, bool);

Unfortunately it throw:

"The as operator must be used with a reference type or nullable type
('(string, bool)' is a non-nullable value type)"

Only work in this way:
Tuple<string, bool> value1 = MethodInfo.Invoke(this, param) as Tuple<string, bool>;

A: You can use a cast expression to cast:
(string value, bool flag) tuple = ((string, bool)) MethodInfo.Invoke(this, param);

But unlike using as, this will crash if the return value of Invoke is not a (string, bool). If you don't like that, you can use pattern matching:
if (methodInfo.Invoke(this, param) is (string value, bool flag))
{
    Console.WriteLine($"({value}, {flag})");
    // assign it to a new variable if you want it as one "thing":
    (string value, bool flag) tuple = (value, flag);
}