text:
Q: I want cubeTextureLoader cube map background but it doesn't work, Why? Three js
I want cubeTextureLoader cube map background. but it doesn't work and showing nothing only white background and my object, But I want 3d background. It gives me error like this one-
"Access to image at 'file:///C:/Users/Mili%20Murmu/Documents/Arena_web/Mili/ThreeJs/Bts_music-player/images/posx.jpg' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, chrome-untrusted, https.".
second error -
"Failed to load resource: net::ERR_FAILED".
I don't understand why isn't showing any cube map background? Please help me! How can I solve this?

const scene = new THREE.Scene();

//light
const light = new THREE.PointLight(0xffffff, 1)
light.position.set(2000, 2000, 1500);
scene.add(light);

const ambientlight = new THREE.AmbientLight(0xffffff, 0.2);
scene.add(ambientlight);

//set up camera
// Set up camera
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.3, 10000)
camera.position.set(1300, 0, 0);

  function onWindowResize() {
    HEIGHT = window.innerHeight;
    WIDTH = window.innerWidth;
    windowHalfX = WIDTH / 2;
    windowHalfY = HEIGHT / 2;
    renderer.setSize(WIDTH, HEIGHT);
    camera.aspect = WIDTH / HEIGHT;
    camera.updateProjectionMatrix();
  }

  //  renderer

  //set up renderer
  const renderer = new THREE.WebGLRenderer({antialias : true, alpha : true});
  renderer.setSize(window.innerWidth - 8, window.innerHeight - 8) ;
  renderer.render(scene, camera);
  renderer.setPixelRatio( window.devicePixelRatio );
  renderer.setClearColor("#803855");
  renderer.shadowMapEnabled = true;
  const container = document.getElementById('world');
  container.appendChild(renderer.domElement);

  document.body.appendChild(renderer.domElement);

  controls = new THREE.OrbitControls( camera, renderer.domElement);

  const group = new THREE.Group();
  scene.add(group);

  const imgLoc = "https://eyes.nasa.gov/apps/exo/assets/image/exoplanet/";

  const geometry = new THREE.SphereGeometry (500, 32, 32);
  const material = new THREE.MeshPhongMaterial();
  const planet = new THREE.Mesh(geometry, material);
  group.add(planet);

  const starGeometry = new THREE.BoxGeometry(20, 20, 20);
  const starMaterial = new THREE.MeshBasicMaterial( );
  const starsphere = new THREE.Mesh(starGeometry, starMaterial );
  scene.add(starsphere);

  let loader = new THREE.TextureLoader();
  material.map = loader.load(imgLoc+'GJ_504_b.jpg');
  material.bumpMap = loader.load(imgLoc+'GJ_504_b.jpg');
  material.bumpScale = 8;
  material.specular = new THREE.Color('#000000');

  var textureCubeLoader = new THREE.CubeTextureLoader();
  var path = 'images/';
  var textureCube = textureCubeLoader.load( [ path + 'posx.jpg' , path + 'negx.jpg', path + 'posy.jpg' , path + 'negy.jpg', path + 'posz.jpg' , path + 'negz.jpg' ] );
  scene.background = textureCube;

  const animate = () => {
    requestAnimationFrame(animate);
    planet.rotation.y += 0.001;
    renderer.render(scene, camera);

  };

  animate();

*{
    box-sizing: border-box;
}

body{
    margin: 0;
    padding: 0;
}
#world{
    margin: 0;
    padding: 0;

}

    <meta charset="utf-8">
    <title>BTS_Music Player</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" type="text/css" href="css/style.css">


text:
Q: Prettier doesn't work in VSCode with eslint I want Prettier to auto format my code using eslint rules in VSCode but it shows this error:

Failed to load plugin 'import' declared in 'CLIOptions': Cannot find module 'eslint-plugin-import'
  Require stack:
  - C:\Dev\Tool\Microsoft VS Code__placeholder__.js

Dependencies in package.json:
"devDependencies": {
  "eslint": "^6.4.0",
  "eslint-config-airbnb-base": "^14.0.0",
  "eslint-plugin-import": "^2.18.2"
}

.eslint.js:
module.exports = {
  "env": {
      "commonjs": true,
      "es6": true,
      "node": true
  },
  "extends": "airbnb-base",
  "globals": {
      "Atomics": "readonly",
      "SharedArrayBuffer": "readonly"
  },
  "parserOptions": {
      "ecmaVersion": 2018
  },
  "rules": {
  }
};

redpajama_set_name: RedPajamaStackExchange


text:
Q: Php artisan migrate command I tried to run php artisan migrate but I'm getting an error:

In Connection.php line 664: could not find driver (SQL: select * from
  information_schema.tables where table_schema = homestead and
  table_name = migration) In Connector.php line 67: could not find
  driver.

A: you should run this command , that's because cache
composer dumpautoload


text:
Q: Lookup tables with no exact match (find first value greater than) I'm a beginner with DAX and Power BI. I want to know how you would handle problems like this:
I have two tables; Table A with all my objects and characteristics (e.g. construction year or rental income per month). And Table B a "lookup table" where the boundaries for that class are.
Based on my characteristics, I want to bin/class the building in a calculated column ("Rental class"). So if the rental income is €423 it's under class 1 and if the rental income is €608 it's under class 4
Table A
Building    Construction_year    Rental_income
B1           2016                 €423
B2           1995                 €650
B3           1949                 €720

Table B
Rental_class   Rental_boundary
Under_class_1   €424
Under_class_2   €607
Under_class_3   €651
Under_class_4   €720

This would be my expected result
Building    Construction_year    Rental_income      Rental_class
B1           2016                 €423              Under_class_1
B2           1995                 €650              Under_class_3
B3           1949                 €720              Under_class_4

In Excel, I would use VLOOKUP (TRUE), but in DAX I don't know how to handle this problem.
This situation happens a lot in my data.

A: You need to calculate the first class in Table B with boundary greater than the income in Table A.
Similar to this question, we can use TOPN to find the appropriate boundary and then take the class associated with it.
Lookup Rental_class =
VAR Income = SELECTEDVALUE ( TableA[Rental_income] )
VAR Boundary =
    TOPN (
        1,
        FILTER ( TableB, TableB[Rental_boundary] >= Income ),
        TableB[Rental_boundary], ASC
    )
RETURN
    MAXX ( Boundary, [Rental_class] )

Or you can use a couple CALCULATE functions.
Lookup Rental_class =
VAR Income = SELECTEDVALUE ( TableA[Rental_income] )
VAR Boundary =
    CALCULATE ( MIN ( TableB[Rental_boundary] ), TableB[Rental_boundary] >= Income )
RETURN
    CALCULATE (
        VALUES ( TableB[Rental_class] ),
        TableB[Rental_boundary] = Boundary
    )

Note: If you want to use these for a calculated column, then remove the SELECTEDVALUE wrapper around TableA[Income].


text:
Q: how to change other spinner based on the spinner selected before? i'm trying to change my second spinner based on what i choose in the first spinner without using any json or database. it must be change the spinner below depend on what we choose in the first spinner. i'm trying with the code below but is doesn't work
this is the java code
    Spinner gedungSpn, lantaiSpn, ruangSpn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_kelas);
GedungSpinner();

        if (gedungSpn.getSelectedItemPosition() == 0){
            LantaiSpinnerRektorat();
        }else if(gedungSpn.getSelectedItemPosition() == 1){
            LantaiSpinnerGL();
        }
    }
 public void GedungSpinner(){

        gedungSpn = (Spinner) findViewById(R.id.gedung_spn);
        List<String> list = new ArrayList<String>();
        list.add("Rektorat");
        list.add("Griya Legita");
        ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, list);
        dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        gedungSpn.setAdapter(dataAdapter);
    }

    public void LantaiSpinnerRektorat(){

        lantaiSpn = (Spinner) findViewById(R.id.lantai_spn);
        List<String> list = new ArrayList<String>();
        list.add("Lantai 1");
        ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, list);
        dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        lantaiSpn.setAdapter(dataAdapter);
    }

    public void LantaiSpinnerGL(){

        lantaiSpn = (Spinner) findViewById(R.id.lantai_spn);
        List<String> list = new ArrayList<String>();
        list.add("Lantai 1");
        list.add("Lantai 2");
        list.add("Lantai 3");
        list.add("Lantai 4");
        list.add("Lantai 5");
        list.add("Lantai 6");
        list.add("Lantai 7");
        list.add("Lantai 8");
        ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, list);
        dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        lantaiSpn.setAdapter(dataAdapter);
    }

please help me. maybe some trick could help. i'm also trying that change the adapter on if statement but it still doesnt work at all

A: Replace
        if (gedungSpn.getSelectedItemPosition() == 0){
            LantaiSpinnerRektorat();
        }else if(gedungSpn.getSelectedItemPosition() == 1){
            LantaiSpinnerGL();
        }

with
gedungSpn.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view,
                    int position, long id) {
                if (position == 0){
                   LantaiSpinnerRektorat();
                 }else if(position == 1){
                   LantaiSpinnerGL();
                 }
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
                // TODO Auto-generated method stub

            }
        });


text:
Q: Parsing Get-GPOReport XML files I have created XML files with Get-GPOReport powershell cmdlets. Now I want parse files with XSLT. But I have no idea where I can found XML elements values description.
For example in XML file there is element - ClearTextPassword
      <q1:Name>ClearTextPassword</q1:Name>
      <q1:SettingBoolean>false</q1:SettingBoolean>
      <q1:Type>Password</q1:Type>

which has description - '...Store password using reversible encryption for all users in the domain...' . Where possible to find description of those XML files?


text:
Q: Java - Trying to output to a file where if the user's login is there only replace the balance My program is basically a user's name, and balance, this is stored in a file, when the user updates their profile, I want their balance to update too, but not their name, as they already have it in the file.
The name and balance are split with a comma. In the file it is displayed like this:
Stacey,0.02

(The name is actually a randomly generated number+letter string, but I thought I'd keep it simple here.)
When I try to write to the file with this code, it doesn't write anything.
Code:
        btnSaveUserid.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            String text = txtUserid.getText().toString();
            String balance = beedcoin1Balance.getText().toString();
            File file = new File("d:/users/joel/desktop/code/usersid.txt");
            BufferedReader br = null;
            try {

                String sCurrentLine;

                br = new BufferedReader(new FileReader("d:/users/joel/desktop/code/usersid.txt"));
                List<String> terms = new ArrayList<String>();
                List<String> ttlBalance = new ArrayList<String>();

                while ((sCurrentLine = br.readLine()) != null) {
                    String[] ar = sCurrentLine.split(",");
                    String userid = ar[0];
                    terms.add(userid);
                    System.out.println(terms);
                }
                if(terms.contains(text)) {
                    PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("d:/users/joel/desktop/code/usersid.txt")));
                    Scanner scanner = new Scanner(file);

                    while(scanner.hasNextLine());
                        String line = scanner.nextLine();

                        String[] ar = line.split(",");
                        String userid = ar[0];
                        String bdcv1val = ar[1];
                        int lineNum = 0;
                        lineNum++;
                        if(line.equals(userid)) {
                            Path path = Paths.get("d:/users/joel/desktop/code/usersid.txt");
                            Charset charset = StandardCharsets.UTF_8;

                            String content = new String(Files.readAllBytes(path), charset);
                            content = content.replace(txtUserid.toString(), txtUserid.toString());
                            Files.write(path, content.getBytes(charset));

                            out.println(text + "," + balance);
                            System.out.println("Successfully printed to usersid.txt");
                        }
                }
                else {
                    PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("d:/users/joel/desktop/code/usersid.txt")));

                    out.println(text + "," + balance);
                    System.out.println("Successfully printed to usersid.txt");

                }
            } catch (IOException el) {
                el.printStackTrace();
            } finally {
                try {
                    if(br != null)br.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }

It all takes place in a button's action listener, and this code outputs the "Successfully printed to file" but doesn't actually print it to the file. I'm honestly perplexed, any help would be greatly appreciated.


text:
Q: When destination bit is F does the working register change? (PIC16F Assembly) As far as I know all the operations are done through the working register in PIC16F. In datasheet, it says when the destination bit is W, the result is written into working register, when it is F, the result is written into the file register. What I'm asking is that, when the destination bit is F does the working register change since the operation is done through it? Or does it stay unaffected?
For example;
Assume W = 3, temp = 5, temp2 = 10
INCF temp,F
DECF temp2,F

What are the contents after these instructions?

A: When the destination bit of some instruction is F or 1 the working register W (WREG) never change!
After execution of instruction:
INCF temp,F

...the content of temp register is incremented for 1.
In case:
INCF temp,W

the content of temp register remain unchanged and result temp + 1 is stored in WREG.
You can use MPLAB simuator as part of MPLAB IDE to test any part of your asm code.


text:
Q: How Can I Deselect a Button or Redefine the function of the Return Key in Windows Forms? I'm making a calculator and I'm wondering how to make the enter key work as the equals sign. All other key bindings worked with keypress except delete which required a separate function attached to keydown. However, I set the RETURN key to perform the same function as the equals sign, and it instead just repeats the pressing of the last button pressed.

A: All WinForms have a property to handle this, Accept Button. You can find it right at the top of the Properties window for the form.

If your equal sign button is instantiated when the form is initialized, it should be available in the dropdown menu.

This property will automatically bind a button on your form to the "AcceptButton" which defaults to the ENTER key.
See Form.AcceptButton on the MSDN docs for more info.


text:
Q: Networks-security-related It doesn't relate specifically to any programming language or technique, but still:
You know how you can use programs like Wireshark to read packets going through your computer (or router, more accurately)? These packets can contain secret information that must be encrypted somehow, like username and password for some systems. But even without this information, one can recreate these packets and obtain the same information, no? For example, I can send these packets from my computer, pretend that I've requested the service and obtain access that way to the given system. How is that prevented?
Also, a kind-of-related question: when a router receives a packet, how does it know to which computer to direct it to if multiple computers are connected to it in an LAN?

A: What you describe is called a replay-attack - to prevent this sort of attack the respective protocol needs to have some built-in features (like some unique ID per request and becomes invalid after being received the very first time and/or becomes invalid after a certain amount of time and/or some timestamp etc.).


text:
Q: Move mysql.sock outside from /tmp folder (WHM/cPanel) I currently have problem with mysql.sock file that automatically get created in /tmp folder and it keep filling up the tmp folder. I've been trying to move it out from /tmp folder to /home/tmp by create a new link using this command
ln -sv /var/lib/mysql/mysq.sock /home/tmp/mysql.sock

and add these lines to my.cnf
[client]
socket = /home/tmp/mysql.sock
[mysql]
socket = /home/tmp/mysql.sock
[mysqld]
socket = /home/tmp/mysql.sock

as well as changing socket path in PHP.ini. Everytime I restarted the mysql it still keep creating in /tmp folder and doesn't even use the one I created in /home/tmp (I check by renaming /tmp/mysql.sock to something while it's running)
Note: I'm checking variables through PHPMyAdmin and for socket it showing /home/tmp/mysql.sock

A: You don't need a symlink.  Remove it.
Change the socket value in my.cnf:
socket   = /home/tmp/mysql.sock

Restart MySQLd.
You shouldn't have to change php.ini:
 ; Default socket name for local MySQL connects.  If empty, uses the built-in
 ; MySQL defaults.

As long as php.ini isn't instructed otherwise, it will just get the socket location from MySQL itself.
You should make sure that the MySQL user has permission to create the socket in /home/tmp/ ... if it doesn't, it would default back to the original /tmp location.


text:
Q: Float Left Jumps content down - Fluid Layout I did my homework on other StockOverflow posts, but couldn't find my answer. Basically I have two pieces of content 1) a project number and 2) a headline.  In javascript I'm setting the width of the project number div to be one eighth of the window width (this works fine).  Then I'm trying to place my headline to the right of it with a left margin of 15%.  It looks fine, except when I reduce my window width- the headline jumps down outside of my projectContainer... The width of my projectContainerHeadline is 100% - and I've tried making this fixed - say 900px - and when i shrink my window it's fine - but when i increase my window size even larger it jumps out again when the headline goes past the 900px mark.  I'm thinking there has to be something I'm missing in order to have a fluid width site work w/ these floats...Also overflow: hidden isn't helping the situation...In essence I want to have my headline div floated to the left without it jumping out of it's block/container.  I need it floated left so that it's margin-left will dynamically update as the width of the left container changes.
My html code can be found here:

01

Test Headline

Test sub-headline

My css can be found here:
.projectContainer{width: 100%; float: left;}
.projectContainerHeadline{height: 130px; float: left; width: 100%; background-color: pink;}
.projectNum{font-family: Helvetica,Arial,sans-serif; font-size: 105px; text-align: right; border-top: 11px solid #d9a870; min-width: 100px; float: left;}
.projectHeadlineText{float: left; margin-left: 15%;}
.projectHeadlineText h2{background-color: blue; margin: 20px 0px 0px 0px;}
.projectHeadlineText h3{background-color: red; margin: 3px 0px 0px 0px;}

A: Does this do what you want?
All I did was change:
.projectHeadlineText{float: left; margin-left: 15%;}

to
.projectHeadlineText{overflow: hidden; }

A: This works for me and hope work for you also.....
.projectHeadlineText{display:inline-block; margin-left: 15%;}


text:
Q: Run latest Firefox or Chrome on Windows XPembedded Is it possible to run the latest versions of Firefox (13.0.0.1) or Chrome (20.0) on Windows XP Embedded?

A: XPe is simply componentized XP, so as long as the browser you want will run on XP (Chrome says it supports XP, I imagine FireFox does too though I didn't check that), then it's possible to make it run on XPe.
That doesn't necessarily mean it will run on your OS, though.  Since XPe is componentized, you have to ensure that all of the OS components that Chrome/FireFox/Etc use are in the OS you build.  If the components are all there and the OS is set up to allow the browser to run (remember, it's an embedded OS and the OS designer can determine what can and cannot execute) then you're good to go.


text:
Q: Change password module in codeigniter Can someone please help me? I'm stuck in this code for a couple of days already. I hope someone could help me..
My problem is if old password is correct and the new password and re-enter password didn't match it still changes the password in the database..
this is my controller:
 public function changepwd(){
  $this->load->view('changepassword'); // this is my view
  $this->load->helper('security');
  $this->load->library('form_validation');
  $this->form_validation->set_rules('opassword','Old Password','required|trim|callback_change["empID"]');
  $this->form_validation->set_rules('npassword','New Password','required|trim');
  $this->form_validation->set_rules('cpassword','Confirm Password','required|trim|matches[npassword]');

  if ($this->form_validation->run() == FALSE){

    echo validation_errors("
<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×</button>","
");

  }

}

public function change($id){
  $session_data = $this->session->userdata('logged_in');
  $query=$this->db->query("select * FROM employee WHERE empID= " .$this->session->userdata('empID'));

  foreach ($query->result() as $my_info) {
      $db_password = $my_info->password;
      $db_id = $my_info->empID;
  }

  if((md5($this->input->post('opassword', $db_password)) == $db_password) && ($this->input->post('npassword') != '') && ($this->input->post('cpassword')!='')) {

      $fixed_pw = md5($this->input->post('npassword'));
      $update = $this->db->query("Update employee SET password='$fixed_pw' WHERE empID='$db_id'")or die(mysql_error());
      $this->form_validation->set_message('change','
×
      Password Updated!
');

  } else {
      $this->form_validation->set_message('change','
×
      Wrong Old Password!
');

  }
}

A: md5($this->input->post('opassword', $db_password)) == $db_password)
  && ($this->input->post('npassword') != '')
  && ($this->input->post('cpassword') != '')

The first line checks that old password is correct. The second two lines check if that new and confirmed passwords are not empty.
Try adding a term that checks that the passwords are also equal:
... && ($this->input->post('npassword') == $this->input->post('cpassword'))

Might work.
There are other things that worry me with your code. But that's another story. (Read about SQL injections, the MVC pattern and how to safely store user passwords in a database)


text:
Q: Create a Signal from a List Is it possible to create a Signal from a List? Essentially what I want is something with the signature List a -> Signal a. I know that a Signal represents a time-varying value and so something like this doesn't actually make any sense (i.e. I can't think of a reason to use it in production code).
I could see applications of it for testing though. For example, imagine some function which depended on the past values of a Signal (via foldp for instance) and you wanted to make assertions about the state of the system given the signal had received values x, y, and z.
Note that there wouldn't have to be anything special about the Signal denoting that it only would ever receive a fixed number of values. I'm thinking of it more like: in production you have a Signal of mouse clicks, and you want to test that from a given starting position, after a given set of clicks, the system should be in some other known state. I know you could simulate this by calling the function a fixed number of times and feeding the results back in with new values, I'm just wondering if it is possible.

A: I guess it's possible. You use a time-based signal, and map the values from the list over it:
import Time
import Graphics.Element exposing (show)

list = [1..10]

signalFromList : List a -> Signal a
signalFromList list =
  let
    (Just h) =
      List.head list

    time =
      Time.every Time.second

    maybeFlatMap =
      flip Maybe.andThen

    lists =
      Signal.foldp (always <| maybeFlatMap List.tail) (Just list) time
  in
    Signal.filterMap (maybeFlatMap List.head) h lists

main = Signal.map show <| signalFromList list

However!
It shouldn't be hard to do testing without signals. If you have a foldp somewhere, in a test you can use List.foldl over a list [x,y,z] instead. That should give you the ability to look at the state of your program after inputs x, y, z.

A: I don't think there is any way it can be done synchronously in pure elm (Apanatshka's answer illustrates well how to set up a sequence of events across time and why it's a bad idea). If we look at how most Signals are defined, we'll see they all head down into a native package at some point.
The question then becomes: can we do this natively?
f : List a -> Signal a

I often think of (Signal a) as 'an a that changes over time'. Here we provide a List of as, and want the function to make it change over time for us.
Before we go any further, I recommend a quick look at Native/Signal.js: https://github.com/elm-lang/core/blob/master/src/Native/Signal.js
Let's say we get down to native land with our List of as. We want something a bit like Signal.constant, but with some extra behaviour that 'sends' each a afterwards. When can we do the sending, though? I am guessing we can't do it during the signal construction function, as we're still building the signal graph. This leaves us a couple of other options:

*

*something heinous with setTimeout, scheduling the sending of each 'a' at an appropriate point in the future

*engineering a hook into the elm runtime so that we can run an arbitrary callback at the point when the signal graph is fully constructed

To me at least, the former sounds error prone, and I hope the latter doesn't exist (and never does)!
For testing, your suggestion of using a List fold to mimic the behaviour of foldp would be the way I would go.


text:
Q: Checking to see if a user has a licence for a managed package So I'm aware that there is a method on UserInfo called isCurrentUserLicensed which lets you check if the user running the code has a licence for a namespace that you specify, i.e. for a particular managed package.
What I want to know is whether there is a way I can test to see if some other user (assume I have their ID) has a licence for a particular package. Has anybody found a way to do this?

A: This is possible by querying on the UserPackageLicense object, available as of Summer 14, as described in my answer to this post:
Get the list of users licensed for a managed package
private static boolean IsUserLicensedForPackage(
    String userId, String packageNamespace
) {
   return [
       SELECT count()
       FROM UserPackageLicense
       WHERE PackageLicense.NamespacePrefix = :packageNamespace
       AND UserId = :userId limit 1
   ]==1;
}

User u = [select Id from User where Name = 'Grace Hopper' limit 1];

System.debug('Does Grace have a license? ' +
    IsUserLicensedForPackage(u.Id,'skuid') ? 'Yes!' : 'No :('
);

A: I know of no inbuilt way to do this (Although my employer is absolutely desperate for it).
The way that we track if a user is licensed for our managed package is whether or not they have one of our permission sets assigned to them.
However there is one enormous caveat. If the license for the managed package is revoked, the permission set remains assigned to the user. This is a significant drawback and can result in false positives, but short of a screen scraping solution it's all we've got.
There is an idea on the idea exchange that is close to what you are trying to achieve.


text:
Q: SQLSTATE[23000]: Integrity constraint Error when updating products via CRON SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`magento_database`.`catalog_product_entity_media_gallery_value`, CONSTRAINT `FK_CAT_PRD_ENTT_MDA_GLR_VAL_VAL_ID_CAT_PRD_ENTT_MDA_GLR_VAL_ID` FOREIGN KEY (`value_id`) REFERENCES `catalog_produc)

I have scoured the internet but nothing seems to work. I have seen the Magento DB repair tool but I believe that would make things more complicated.

A: You are trying to update a row in catalog_product_entity_media_gallery_value, but the foreign key on catalog_product_entity (I guess) is missing.
Therefore you try to write a media gallery image, without having a product.
The solution for this is, to check why the entry in catalog_product_entity doesn't exist. Maybe the product_id value on your write to catalog_product_entity_media_gallery_value is null?
It is no problem with the defined foreign key, but with enforcing of this dependency.
Be careful when debugging this. This may all happen inside a transaction, then it is hard to look inside it - at least I don't know how to do this.


text:
Q: Silex 500 error index.php
use Silex\Application;
require_once __DIR__ . './vendor/autoload.php';

$app = new Application();
$app->run();

htaccess
<IfModule mod_rewrite.c>
    Options -MultiViews
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [QSA,L]
</IfModule>

visiting
127.0.0.1/index.php

I get

500 internal error.

Any solutions please?

A: Your htaccess files should not be named .htaccess.php but just .htaccess.
Then make sure every files have the good rights (apache has access to it).
Be also sure that mod_rewrite is enabled.


text:
Q: Jekyll - Assembing a model I have some content originating from yaml and markdown in the normal Jekyll pattern.
I also have various content pulled in from an API that I access via Jekyll data.  For example, I can link a page to its related data file with the following.
sita.data.API[page.api-id]

This is working quite nicely.  However, I only use say the image from the site.data if there is none available in front-matter.  I have achieved this but have all sorts of if statements in my template to control the output of say a URL to an image.
I've attempted to put in an include but this led to trouble when looping over site.pages, for example, outputting thumbnails for a collection of posts.
I really want to pull the data from site.data into the page's Jekyll model.  So that all of the default values and other logic can be hidden from the templates.  I can iterate over site.pages without having lots of copy and paste code scattered across the site or attempting to push the include tag beyond what it was designed for.
Is this something that can be done with a plugin?
Failing that, I could use a gulp or other build step that merged the data from the markdown files and the site.data into the third set of files - probably markdown?  This solution feels like a step away from Jekyll towards using something like gatsby.

A: As per the Jekyll docs

... a generator [plugin] can inject values computed at build time for template variables.

There are some quite usable examples on the page as linked.
module Composite-model
    class Generator < Jekyll::Generator
      priority :lowest
      def generate(site)

        # get the target from collections.
        # you could also target site.page or site.post with various filters.
        customCollection = site.collections['my-collection']

        customCollection.each do |item|

          # Get data from another source and link on id.
          apiId = item["api-id"].to_s
          apiData = site.data["api"][apiId]

          # attach data to collection item
          item.data['api-data'] = apiData

          # please forgive the messy logic, first bit of ruby.
          # Will refactor and update
          if apiData  && apiData["images"]
              singleImage = apiData["images"].length == 1
              item.data['single-image'] = singleImage

              if item["custom-image"].to_s.strip.empty?
                imageUri = apiData['images'][0]['uri'].split('/').last
                image = File.join("/assets/images/", apiId, imageUri)
                item.data['image'] = image
              else
                item.data['image'] = item["custom-image"]
              end
          else
            item.data['image'] = item["custom-image"]
          end
        end
      end
    end
  end

N.B
It looks like you can not overwrite a page variable from within a generator plugin.
For example, I first tried to transform item.image directly from the front-matter.  However, this did not work so have page front matter use custom-image and then image is first used by this generator.  Might be worth a different question.


text:
Q: What does "the closest it was expected to be" mean in context *Tapah = A typhoon.
*Busan = The country's second-largest city.

Tapah was expected to pass about 130 kilometers southeast of Yeosu, South Jeolla Province, at around 6 p.m. Sunday and 170 km south of Busan at around 9 p.m. The closest it was expected to be to the country's second-largest city was 50 km at around 10 p.m. It would then pass about 60 kilometers northeast of Korea's easternmost islets of Dokdo in the East Sea at around 6 a.m. Monday, according to the weather agency.

What I was wondering is the bolded phrase.
The closest what is 50 km? A distance? And 50 km of what? In a 50 km radius, or 50 km to the southeast?
I'm not a native speaker so I'm not sure you could omit some parts like this in a official written paper. Inform me please if this is written well or not. If it is done correctly, how could a native speaker notice what is omitted or not and interpret this naturally? Just from background knowledge and the context?

A: "It" in the bold phrase means "the typhoon", so this just means that at 9pm the Typhoon was predicted to be 170km South of Busan, and at 10pm it was expected to be 50km away from Busan (the direction isn't given)
50km is the distance from the city to the typhoon at 10pm.  Nothing essential is omitted in the sentence. It is grammatically complete.


text:
Q: Reading Checkbox FormControl value in Angular Reactive Form I have the following code
if (this.myForm.value['isDefault'] === true)

Where isDefault is a checkbox FormControl. Now if the checkbox is checked I am expecting this.myForm.value['isDefault'] will result in true. When I alert this, it indeed shows true but this comparison does not result in true.

A: You need recheck your form and code in TS file. I reproduce it still work correctly.
HTML

        <form [formGroup]="theForm" (submit)="check()">
            Check? <input type='checkbox' formControlName="firstCheck"/>
  <input type="submit" value="check">
    </form>

TS
export class AppComponent {

  theForm: FormGroup;
  constructor(private fb: FormBuilder) {
    this.theForm = fb.group({
      firstCheck: false
    })
  }

  check() {
    console.log(this.theForm.value['firstCheck'] === true)
  }
}

Demo https://stackblitz.com/edit/checkbox-reactive-aagwtp?file=app%2Fapp.component.ts

A: If you want a value of a form control , you can also access using form.get('key').value.
I forked @Hien Nguyen's stckblitz :
Refer : https://stackblitz.com/edit/checkbox-reactive-hdwhsj?file=app/app.component.ts
So i would use : this.myForm.get('isDefault').value


text:
Q: how to check if a non primitive java array has a certain element I'm trying to search a java array that has values of a class called Tickets has a certain ticket object...the usual for loop with if statements used for primitive data types does not work
I have tried the stuff below
public  Ticket retrieve(String ticketID){
    Ticket retur;
    for(int i=0;i<numTickets;i++){
        if (tickets[i].equals(ticketID)){
        retur = tickets[i];
        }
    }
    return retur;
}

I'm getting the error retur may not be initialised.

A: You have to initialize Ticket object because if your array don't have any object with same ticketId then your Ticket oibject remain uninitialized. Your Comparison is also wrong. you have to compare ticketId with some field of Ticket object. like tickets[i].getId().equals(ticketID)
public Ticket retrieve(String ticketID){
        for(int i=0;i<numTickets;i++){
            if (tickets[i].equals(ticketID)){
               return tickets[i];//If tickets[i] is a `String` object then you have to convert it into `Ticket` object before returning. Or if `tickets[i]` is a `Ticket` object then you comparison is wrong.
            }
        }
        return null;
 }


text:
Q: $\sum\limits_{n=1}^{\infty}\arctan{\frac{2}{n^2+n+4}}$ $$\sum\limits_{n=1}^{\infty}\arctan{\frac{2}{n^2+n+4}}$$
We know that : $\arctan{x} - \arctan{y} = \arctan{\frac{x-y}{1+xy}}$ for every $ xy > 1 $
I need to find two numbers which satisfy: $ab = n^2+2n+3 $ and $ a-b =2$ in order to telescope.
Edit: I am very sorry on the denominator it should have been $n^2+n+4$ not $n^2+2n+4$
Similarly here :
$$\sum\limits_{n=1}^{\infty}\arctan{\frac{8n}{n^4-2n^2+5}}$$
The result should be $ \arctan 2 $ on the first one and $ \pi/2 + \arctan2  $ on the second one.

A: Hint:
$$\dfrac2{n^2+n+4}=\dfrac{\dfrac12}{1+\dfrac{n(n+1)}4}=\dfrac{\dfrac{n+1}2-\dfrac n2}{1+\dfrac n2\cdot\dfrac{n+1}2}$$
For the second, $$\dfrac{8n}{n^4-2n^2+5}=\dfrac{\dfrac{(n+1)^2}2-\dfrac{(n-1)^2}2}{\dfrac{(n+1)^2}2\cdot\dfrac{(n-1)^2}2+1}$$

A: $$\sum\limits_{n=1}^{\infty}\arctan{\frac{2}{n^2+n+4}} = \sum\limits_{n=1}^{\infty}\arctan{\frac{2(n+1)-2n}{n(n+1)(1+\frac{4}{n(n+1)})}} =
\sum\limits_{n=1}^{\infty}\arctan{\frac{\frac{2}{n}-\frac{2}{n+1}}{1+\frac{2}
{n}\cdot\frac{2}{n+1}}} =\sum\limits_{n=1}^{\infty}\arctan{\frac{2}{n}-\arctan{\frac{2}{n+1}}} =\arctan2$$


text:
Q: Is there a way to keep my navbar-right to the right and always visible at top of page when scrolling? Initial load:

After scrolling:

I'm trying to have a fixed nav at the top of the viewport. So as you scroll down the page the nav is always visible.  My problem is that I have my navbar brand set to the left of the nav and my links to the rest of my page set to the right. When I add position fixed to the navbar brand it works fine (the brand stays visible as I scroll down the page), however no matter what I've tried when I add position fixed to any other classes, id's, or elements involving the links set to the right, they end up getting fixed to the left and overlaying the brand or sitting directly under the brand.  I cannot figure out why this is happening.
I've tried adding position fixed to various classes within the navbar with no luck.  I also tried forcing the items to the right with float: right!important.  Most of the articles I've found suggest adding position: fixed to the .nav class, but when I do that the items are pushed to the left.  I included the html for my nav as well as the CSS for the nav, the background-video and the modal I link to in the nav just in case there is some reason this may be causing the problem.  Thanks for any help!  It's much appreciated.
HTML

allicndev

About

Portfolio

            Resume

Skills

Contact

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

Resume

        <embed id="modal-embed" src="assets/anresume.pdf">

        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

CSS
* {
  box-sizing: border-box;
}
html, body {
  width: 100%;
  height: 100%;
  margin: 0px;
  padding: 0px;
  overflow-x: hidden;
  position: relative;
}
body {
  margin: 0;
  font-family: 'Montserrat', Arial, sans-serif;
  font-size: 17px;
}
#myVideo {
  position: absolute;
  right: 0;
  bottom: 0;
  min-width: 100%;
  min-height: 100%;
}
.container-fluid {
  padding-right: 30px;
  /* position: fixed; */
}
nav {
  height: 75px;
  display: border-box;
  color: white;
  font-size: 12px;
  text-align: center;
  position: fixed;
  /*z-index: 10px;*/
}
nav.navbar {
  width: 100%;
}
.navbar-header {
  position: fixed;
}
.nav.navbar-nav.navbar-right > li {
  padding-top: 15px;
  margin: 10px;
}
.nav > li > a {
  display: inline;
  padding-left: 0;
  padding-right: 0;
  padding-top: 5px;
  background-color: transparent;
}
.navbar-nav>.active>a, .navbar-nav>.active>a:focus, .navbar-nav>.active>a:hover {
  background-color: transparent;
}
a.db-line {
  transition: white .3s linear;
}
a {
  color: white;
  text-decoration: none;
}
a > h3 {
  color: white;
  text-decoration: none;
}
a:hover {
  color: #f97f04;
}
/* a:visited {
  color: #EDCF10;
} */
.modal {
  display: none;
  height: 100%;
  left: 10px;
  position: fixed;
  top: 0;
  width: 100%;
}
.modal.open {
  display: block;
}
.modal-header,
.modal-footer {
  height: 75px;
}
.modal-content,
.modal-footer {
  width: 100%;
}
.modal-footer {
  bottom: 0px;
}
#modal-embed {
  width: 100%;
  height: 75vh;
}

If possible I expect the brand ("allicndev") to be to the left top and the links ("about", "portfolio", "resume", "skills", and "contact") to be to the right top and the whole nav to stay visible this way as the page is scrolled through or links targeted to sections are clicked.

A: Yes, you should use the class fixed-top for fixed top navbar while scrolling

A: The markup in your example is for Bootstrap 3, so that's problem #1, given that you've tagged this Bootstrap 4.
Assuming Bootstrap 4 is correct, adding the correct markup and classes seems to create what you're describing: https://jsfiddle.net/4rtjcpzm/1/

    allicndev

About

Portfolio

        Resume

Skills

Contact

The ml-auto (margin-left: auto, if you check the source) class is what allows the links to slide all the way to the right. fixed-top and sticky-top will both stick the navbar to the top of the viewport.
sticky-top is probably the better class to use in terms of not needing to bump the body content down (the padding-top you see in the CSS part of the fiddle), but that depends on whether you know (or care) if most of your expected visitors will use a browser that supports position: sticky;.
As an aside, do note that a > h3 (an H3 element inside an anchor element) is not (by default) valid HTML;  is an inline element, and
 is a block element, which is invalid according to the HTML spec.


text:
Q: How to use list comprehension to mutate the original list Why does list comprehension not change the original list like a for loop? List comprehension seems like a simpler solution.
Problem statement:
Implement a function map_mut that takes a list as an argument and maps a function f onto each element of the list. You should mutate the original lists, without creating any new lists. Do NOT return anything.
Wrong way with list comprehension:
def map_mut(f, L):
    '''
    >>> L = [1, 2, 3, 4]
    >>> map_mut(lambda x: x**2, L)
    >>> L
    [1, 4, 9, 16]
    '''
    L = [f(x) for x in L]

Right way with a for loop:
def map_mut(f, L):
    for i in range(len(L)):
        L[i] = f(L[i])


text:
Q: Why return statement works for void as return type in C? NOTE: I am using windows 7 and  gcc compiler on code blocks IDE.
I have found out that all forms of return
statements can be used if the return type
of function is void
for example:
void message() //If i skip this declaration still it works
main()
{
    message();
}
void message()
{
    return 5; //also return 5.0 and return a(some variable) also works
}

Since, void refers to 'nothing is returned' then how can we use return statements here. Does it mean that all programs return something whether it is void or other return type?
One more query I have regarding void as return type:
If I use this program
main()
{
    printf("%d",message());
}

void message()
{
}

It gives output as 1,
and doesn't give error
But I get an error if I use this:
void message(); //when I use the declaration

main()
{
    printf("%d",message());
}

void message()
{

}

Why does it happen?

A: I am not very sure about C89, but in C11, I can see in chapter §6.8.6.4

A return statement with an expression shall not appear in a function whose return type
  is void. [...]

So, your code violates the standard.
Regarding the second part,

*

*while missing declaration, due to the now-obsolete type-defaults-to-int property, it appeared to work, but it actually invoked undefined behavior, because, you're supplying a void type as int argument.

*While having a forward declaration (with return type as void), due to mismatch of return type, error is prominent.

A: The C11 standard draft n1570 says the following in the foreword:

Major changes in the second edition [that is, C99] included:
[...]
— return without  expression  not  permitted  in  function  that  returns  a  value  (and  vice versa)

C89 standard then says the following:

Constraints
A return statement with an expression shall not appear in a function whose return type is void.

However, nothing is mentioned about prohibiting a return statement without an expression appearing in a function whose return type is not void.
Thus returning a value from void is not correct in C89 either.

Note that main() without return type is not allowed by C11 either. However, GCC is quite relaxed about many of these border cases, unless -pedantic-errors option is provided.


text:
Q: Skipping analyzing "feedparser.util": module is installed, but missing library stubs or py.typed marker How do I fix this error? It seems feedparser does not support mypy typings? I could not find a typeshed implementation for feedparser
UPDATE 1
I see an option called ignore_missing_imports that I can add to pyproject.toml. Isn't it a bad idea to do this?

A: You can ignore missing imports only for this specific package by adding a [tools.mypy.override] section in pyproject.toml. This way you don't need enable the flag on everything.
[[tool.mypy.overrides]]
module = "feedparser.*"
ignore_missing_imports = true

The work for supporting typing in feedparser has been merged to the develop branch and you should be able to remove this workaround when it is released.


text:
Q: When execute "AudioKit.start()", an error occorent I have push the recordViewController that record audio by AudioKit from homeViewController which is an emptyViewController,and I have write code in APPDelegate.swift like this:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions:[UIApplicationLaunchOptionsKey: Any]? = nil) -> Bool {
do {
    try AVAudioSession.sharedInstance().setActive(true)
    try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
}catch{

}
UIApplication.shared.beginReceivingRemoteControlEvents()
return true
}

then when it push to recordViewController,show this message

'[AVAudioEngineGraph.mm:1266:Initialize: (err =
AUGraphParser::InitializeActiveNodesInOutputChain(ThisGraph,
kOutputChainOptimizedTraversal, *GetOutputNode(),
isOutputChainActive)): error -10875,
RecorderViewController.swift:stetupConfigs():89:AudioKit did not
start!'


text:
Q: A JTextPane that looks like a JTextArea Since we started on the wrong foot, I ask again, previous question deleted. Please check it out, the border of JTextPane IS NOT the same as the border of JTextArea, not by default:
So I need a JTextPane that looks exactly like a JTextArea.
I set the border of the JTextPane to new JTextArea().getBorder();. It looks like it should, however, focus isn't being drawn properly... How do I fix it?
I'm using Nimbus here, if it's any help...
THE SSCCE:
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JTextPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.UIManager.LookAndFeelInfo;

public class Main
{
public static void main(String[] args)
{
    for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels())
    {
        if ("Nimbus".equals(info.getName()))
        {
            try
            {
                UIManager.setLookAndFeel(info.getClassName());
            }
            catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e)

            {
                System.out.println("No Nimbus!");
            }

            break;
        }
    }

    JFrame a = new JFrame("Test");
    a.setSize(200, 400);
    a.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    a.getContentPane().setLayout(new BoxLayout(a.getContentPane(), BoxLayout.Y_AXIS));

    JTextPane[] b = new JTextPane[5];

    for (int i = 0; i < 5; i++)
    {
        b[i] = new JTextPane();
        b[i].setBorder(new JTextArea().getBorder());
        b[i].setText(Integer.toString(i));
        a.getContentPane().add(b[i]);
    }

    a.setVisible(true);
}
}

I've set the border to be the same one as on JTextArea, but the focus is not being painted or moved properly. If you comment out that line, there will be no border whatsoever.

A: If you add a Focus Listener that forces a repaint, then the strange behvaiour goes away.
Example:
for (int i = 0; i < 5; i++) {
    final JTextPane b = new JTextPane();
    b.setBorder(new JTextArea().getBorder());
    b.addFocusListener(new FocusListener() {

        @Override
        public void focusGained(FocusEvent arg0) {
            b.repaint();
        }

        @Override
        public void focusLost(FocusEvent arg0) {
            b.repaint();
        }

    });
    b.setText(Integer.toString(i));
    a.getContentPane().add(b);
}

This seems like a hack fix, but I am not sure why this is happening.


text:
Q: MongoDB index ascending or descending matter In MongoDB if I run a query like the following to get the latest trade:
db.trades.find({ sym: 'AAPL' }).sort({ d: -1 }).limit(1)

If the index on d is created as { d: 1 }. I.E. does it matter if the index sort is ascending or descending? Also, I have an index on sym as well { sym: 1 }.


text:
Q: Eliminate a user who meets the condition, even though they may not meet the condition in other rows I have a query that is (amongst other things) looking for people who are available for a shift on a certain day.
SELECT secud_id, secud_fname, secud_sname, user_id, user_owner, user_level, shift_start, GROUP_CONCAT(DISTINCT uq_name SEPARATOR ' ') quals
FROM user_data
INNER JOIN users ON user_data.secud_ulink = users.user_id
LEFT JOIN user_quals ON users.user_id = user_quals.uq_user
LEFT JOIN shifts ON shifts.shift_user = users.user_id
WHERE users.user_owner = 2
AND users.user_level= 'Personnel'
AND (date(shifts.shift_start) <> '2016-03-16' OR date(shifts.shift_start) IS NULL)
AND users.user_active = 1
GROUP BY users.user_id
ORDER BY secud_sname ASC

To explain the structure, users is the users main table, user_quals holds various certificates etc (and may be empty for that user, or have many entries), user_data holds assorted bits of information for the user & shifts holds the shift dates and times, locations etc (which may also have lots or none).
I'm mostly getting what I want - a list of active users with their qualifications who belong to a certain organisation (user_owner) with the user_level of Personnel who don't have a shift on that date, however they are showing up if they are found to have a shift on another date which of course meets the WHERE clause.  If they have a shift on that date, even though they may be returned in other rows, I don't want them to appear.
Any guidance is much appreciated.

A: You could also address it in the JOIN to shifts, narrowing the selection from the table to only the target date:
LEFT OUTER JOIN shifts ON shifts.shift_user = users.user_id and date(shifts.shift_start)='2016-03-16'

Then in your WHERE clause, target only the null records for shift_start:
WHERE shift_start IS NULL

or
LEFT OUTER JOIN shifts ON shifts.shift_user = users.user_id and date(shifts.shift_user) = '2016-03-16'
WHERE users.user_owner = 2
  AND users.user_level= 'Personnel'
  AND date(shifts.shift_start) IS NULL
  AND users.user_active = 1
GROUP BY users.user_id
ORDER BY secud_sname ASC

A: It's not exactly clear what you are needing to accomplish. Example data and example output would go a long ways towards clearing that up. Setting up a SQLfiddle http://sqlfiddle.com might help you get an answer faster.
I suspect that the issue is with the predicate on shift_date in the WHERE clause.
It sounds like the result you are after could be produced by an "anti-join" pattern. That starts as an outer join, in this case, return all rows from users along with matching rows from shifts.
SELECT u.user_id
  FROM users u
  LEFT
  JOIN shifts s
    ON s.user_id = u.user_id

In this case, you want to find matching shifts starting on a given date...
   AND s.shift_start >= '2016-03-16'
   AND s.shift_start <  '2016-03-16' + INTERVAL 1 DAY

"But wait", you say, "those are the rows I don't want."
Right.
But it's an outer join, so we are getting all rows from users. If there are any matching rows in shifts, we get those rows too. For any rows in users that don't have a matching rows (meeting our specified criteria in the ON clause), the values of the columns from shifts will be NULL.
The trick is to exclude the rows that had a match. Any real rows from shifts will have non-null values in shift_start. (We're guaranteed that, because of the condition in the ON clause. A NULL value of shift_start wouldn't satisfy the condition.) So, we only want to return the rows that have a NULL value for shift_start. And adding a WHERE clause with that condition is pretty easy:
 WHERE s.shift_start IS NULL

Any user with a matching row in shifts will not be returned. And so what we get back is just the users that don't have a shift starting on the specified date.
Putting that all together:
SELECT u.user_id
  FROM users u
  LEFT
  JOIN shifts s
    ON s.user_id = u.user_id
   AND s.shift_start >= '2016-03-16'
   AND s.shift_start <  '2016-03-16' + INTERVAL 1 DAY
 WHERE s.shift_start IS NULL

And obviously, this isn't the only query pattern that will return that result. We could use a query with a NOT EXISTS predicate to get an equivalent result.
The anti-join pattern is a bit much to get your brain wrapped around. But once you master it, it's a powerful tool to keep in the SQL toolbelt.
I've omitted the other tables for the sake of clarity. I'm expecting you will be able to fill out the select list, add in joins to the additional tables, add the GROUP BY, and so on, to build the actual set you need.
   AND u.user_owner = 2
   AND u.user_level= 'Personnel'
   AND u.user_active = 1

If this isn't the result you were looking for, then I misunderstood the specification. Example data and the expected output would go a long ways to helping me understand the specification.


text:
Q: Ethereum smart contract outside Ethereum network Is it possible to use smart contract with cryptocurrency other than Ethereum?
Basically what i want is to use smart contract in place of traditional escrow method.

A: Yes! If I am understanding you correctly, you're referring to a token? With Ethereum, you are able to make your own ERC-20 token via a smart contract. Although the title of the question seems to be referring to inter-blockchain communication. This is also possible. Here are a few examples of projects that incorporate inter-blockchain communication:

*

*Aion

*Polkadot

*Cosmos
Recently, Bancor and Aion teamed up to provide inter-blockchain liquidity which allows for "both data and value to transfer between chains".
Amberdata.io is working on implementing data analytics for inter-blockchain communication. For now, if you're interested in Aion you can explore their chain here.
In regards to an escrow contract here is a tutorial on how one might build it.
Hope that helps!


text:
Q: Update command in Fluent NHibernate I am trying to update an object after retrieving it from a database.
This fires 2 queries , one for the select and the other for the update, is there any way of update an object using Fluent NHiberNate firing only one query ?
 My code is as below:
var userProfile = userProfileRepository
     .Find(x => x.ClientId == clientId)
     .FirstOrDefault();
/*  update UserProfile object here */
userProfileRepository.SaveOrUpdate(userProfile);

the SaveOrUpdate Method looks as such :
public bool SaveOrUpdate(T instance)
{
    using (var session = SessionManager.OpenSession())
    {
        using (var transaction = session.BeginTransaction())
        {
            session.SaveOrUpdate(instance);
            transaction.Commit();
        }
        return true;
    }
}

A: In case that your issue is:

*

*regardless of what I do, SaveOrUpdate() always sends SELECT then UPDATE

You should check the doc:
5.1.4.7. Assigned Identifiers

If you want the application to assign identifiers (as opposed to having NHibernate generate them), you may use the assigned generator. This special generator will use the identifier value already assigned to the object's identifier property. Be very careful when using this feature to assign keys with business meaning (almost always a terrible design decision).
Due to its inherent nature, entities that use this generator cannot be saved via the ISession's SaveOrUpdate() method. Instead you have to explicitly specify to NHibernate if the object should be saved or updated by calling either the Save() or Update() method of the ISession.

So, if your Fluent configuration sets the ID to be assigned - NHibernate has no other way then check if it

*

*exists

*or is new

because used method was SaveOrUpdate()
Solution(s)
1) Change the ID to be generated by DB or NHiberante 2) use explicit Update()

A: Are you trying to create an
 UPDATE ... WHERE ...

statement?
AFAIK the NHibernate way to do this, is to select the appropriate objects (using the WHERE clause), update the fields, and persist them again.
var tempObjects = _session.Query<myObject>.Where(o => o.Id > 500);

// update proxy objects
foreach (var o in tempObjects)
{
   o.MyValue = updatedValue;
}

// commit updated objects
_session.Update(tempObjects);

To be honest, we've used ISession.CreateSQLQuery ourselves. I hate using SQL in code because it breaks in refactoring, but if you must - here's how:
_session.CreateSQLQuery(
     @"UPDATE [MyTable] SET [MyValue]=:updatedvalue WHERE Id > 500")
    .SetParameter("updatedvalue", updatedValue)
    .ExecuteUpdate();


text:
Q: Google wiki to Eclipse help conversion possible? Which tools? is there a way to generate Eclipse help files from Google wiki pages as it is possible to generate such ones from twiki or mediawiki pages via the mylin wikitext plugin?
Or are there converter available to bring google wiki files into mediawiki or twiki format?
In hope for help,
omnaest

A: Since it seems that anyone has an idea, I created an own ant task for text file conversion.
If there is interest in an example of converting textile pages into google wiki pages you can look at
ant script example
There is the ant task used to convert textile pages into html and google wiki and then to deploy.
The important ant target of the buid.xml is "convertWikiFolder" and it looks like:
<target name="convertWikiFolder" depends="dircopyWikiFolder">
  <echo message="Converting textile files for wiki folder."/>
  <textFileContentConverter fileNameSource="${folderWikiTarget}" fileNameRegexFilter="(.*)\.textile$" fileNameReplacement="$1.wiki" fileNameRegexFilterAndReplacementPatterns="regexFilterFromTextileToGoogleWiki.xml" deleteSourceFileAfterConversion="true"/>
</target>

It uses the "regexFilterFromTextileToGoogleWiki.xml" to define regular expressions which translates the different wiki/text syntax.
To convert other wiki syntax files this regex file has to be adapted.
The related ant task binary is located under "bin/TextFileContentConverter-0.0.1-SNAPSHOT-jar-with-dependencies.jar"

A: Google wiki pages aren't directly supported by Mylyn WikiText.
For MediaWiki take a look at the Eclipse documentation on MediaWiki To Eclipse Help which provides an Ant task for generating Eclipse Help from a MediaWiki.  Also DocumentationGuidelines/CrowdSourcingExample provides a concrete example of how this can be done.


text:
Q: AWS Cognito Pricing confusions I'm checking aws cognito pricing, their explain make me confuse. They wrote:

Users who sign in through SAML or OIDC federation:
For users who sign in through SAML or OIDC federation, the price for MAUs above the 50 MAU free tier is $0.015.

So What is differences between sign in directly with User Pool credentials and via SAML?
https://aws.amazon.com/cognito/pricing/

A: You can connect a Cognito user pool to a SAML IDP (Azure, Okta, etc.) and use a Cognito App client to allow users to authenticate with your SAML IDP (i.e. log in with their company Okta account) and assign an AWS IAM role through the Cognito pool.
It is a bit more complicated to set up a SAML provider, but a common requirement for corporate applications. If you do not need to integrate with another IDP, then you can use the standard Cognito user pool, which is much cheaper.


text:
Q: Definir o nome de uma propriedade dinamicamente em VB.NET Tenho uma classe com uma propriedade pública nela. Como segue no exemplo:
Public Property exemplo As List(Of Uso)
        Get
            Return x_exemplo
        End Get
        Set
            x_exemplo = Value
        End Set
    End Property

    Private x_exemplo As List(Of Uso)

Consigo usá-la tranquilamente. Porém, o que preciso é definir o nome dela dinamicamente. Ou seja, o nome "exemplo" não pode ser fixo. As vezes será exemplo2, outras "teste", etc. Isso é possível? Chamar alguma função ou método que defina o nome da propriedade?
No meu arquivo principal, a classe é chamada durante a leitura de um arquivo JSON:
For Each valor In classe-principal.propriedade-da-classe-principal.propriedade-de-outra-classe.exemplo
...
Next

Ou seja, "propriedade-da-classe-principal", "propriedade-de-outra-classe" são nomes das chaves do arquivo JSON. "exemplo" também é, porém é um nome dinâmico, que dependendo do arquivo, muda de nome. Já consegui identificar o nome da chave que é dinâmica, só preciso usar esse nome como 'nome da propriedade', para que eu consiga entrar nela e pegar os valores seguintes do json.

A: Eu não sei qual biblioteca você está utilizando pra deserializar o JSON, mas ela provavelmente oferece uma forma de deserializar para um Dictionary. Neste caso você precisa deserializar para um Dictionary(Of String, Object), daí você acessa a propriedade dinamicamente (pois a chave do dicionário é uma String) e faz um cast de Object pro tipo que você quiser.

A: Seria algo como o método CallByName do Vb?
Você utiliza a chamada do método basicamente por uma String
Por Exemplo:

Sub TestCallByName1()
    'Definir a propriedade Text no TextBox1.
    CallByName(TextBox1, "Text", CallType.Set, "New Text")

    'Obter o valor da propriedade Text no TextBox1.
    MsgBox(CallByName(TextBox1, "Text", CallType.Get))

    'Chamando um método.
    CallByName(TextBox1, "Hide", CallType.Method)
End Sub

Mais informações podem ser obtidas na página oficial da documentação
CallByName da Microsoft


text:
Q: progress bar showing progess scrolling down page reaches end before page does I have a progress bar to show where the reader is when they're scrolling down the web page. The bar seems to work find on short pages. But on long pages, it reaches the end before the user has scrolled to the end. Can anyone tell me what's going wrong please?
html:
<progress value="0"></progress>

css:
progress {
  /* Positioning */
  position: fixed;
  left: 0;
  top: 75px;

  /* Dimensions */
  width: 100%;
  height: 5px;

  /* Reset the appearance */
  -webkit-appearance: none;
     -moz-appearance: none;
          appearance: none;

  /* Get rid of the default border in Firefox/Opera. */
  border: none;

  /* Progress bar container for Firefox/IE10+ */
  background-color: transparent;

  /* Progress bar value for IE10+ */
  color: #c19566;

  z-index: 9999;
}

progress::-webkit-progress-bar {
  background-color: transparent;
}

progress::-webkit-progress-value {
  background-color: #c19566;
}

progress::-moz-progress-bar {
  background-color: #c19566;
}

jquery:
var winHeight = $(window).height(),
    docHeight = $(document).height(),
    progressBar = $('progress'),
                        max, value;

    /* Set the max scrollable area */
    max = docHeight - winHeight;
    progressBar.attr('max', max);

    $(document).on('scroll', function(){
        value = $(window).scrollTop();
        progressBar.attr('value', value);
    });


text:
Q: spring mvc @SessionAttributes not binding properly I have a Portlet controller like this. Here I bind a variable to Session. After that it redirects to another controller and renders the jsp .
@SessionAttributes({"attrName"})
public class Controller{
public void manage(ModelMap modelMap)  {
modelMap.addAttribute("attrName", true)
response.sendRedirect(URL_CONTROLLER_2);
}
}

So this redirects to another controller that renders the jsp.
In jsp when I do:
alert("${attrName}")

I get null.
Why am I not able to see the attribute.
Even when I debug and I check ModelMap in controller # 2, the attribute "attrName" is not present in session.

A: AFAIK it's an expected behaviour because @SessionAttributes are not shared among different controllers. Attributes saved this way will be removed from session as soon as next controller is called.


text:
Q: Installing mysql client in django virtual environment I have created a virtual environment,with python 3 and installed django
I cant install mysqlclient ,it says problem with setup.py
jayanthi@jayanthi-Aspire-4920:~$ source env/bin/activate
(env) jayanthi@jayanthi-Aspire-4920:~$ pip install mysqlclient
Collecting mysqlclient
      Using cached mysqlclient-1.3.10.tar.gz
        Complete output from command python setup.py egg_info:
        /bin/sh: 1: mysql_config: not found
        Traceback (most recent call last):
          File "<string>", line 1, in <module>
          File "/tmp/pip-build-4pbezvx6/mysqlclient/setup.py", line 17, in <module>
            metadata, options = get_config()
          File "/tmp/pip-build-4pbezvx6/mysqlclient/setup_posix.py", line 44, in get_config
            libs = mysql_config("libs_r")
          File "/tmp/pip-build-4pbezvx6/mysqlclient/setup_posix.py", line 26, in mysql_config
            raise EnvironmentError("%s not found" % (mysql_config.path,))
        OSError: mysql_config not found
    Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-4pbezvx6/mysqlclient/

A: on Ubuntu you must install the package:
sudo apt-get install libmysqlclient-dev


text:
Q: Multiple related entries split into multiple paragraphs using angew-chem This question is related to "An entry with multiple keys in the related field: is Biblatex expected to split multiple related entries into multiple paragraphs?". However, I am using the biblatex-chem style chem-angew, which has different output.
I am trying to add multiple related entries to a reference. They are related, as the second two publications are corrections of the first two. As in the aforementioned question, the first related entry is placed delimited by a semicolon as it should be.
The Problem: All subsequent entries are delimited only by a comma.
Using the solution of \renewcommand*\relateddelim{} does remove printing on a new line, but it doesn't matter if I have \addcolon, \addsemicolon or anything like that before \addspace.
My MWE (bibliography data stripped of unnecessary information for this MWE):
\documentclass{article}

\usepackage[backend=biber, style=chem-angew]{biblatex}

\RequirePackage{filecontents}
\begin{filecontents*}{\jobname.bib}
@article{Buntin.2008.ange,
  author = {Buntin, Kathrin},
  year = {2008},
  pages = {4671--4676},
  pagination = {page},
  volume = {120},
  journal = {Angew. Chem.},
  related = {Buntin.2008.anie,Buntin.2009.ange,Buntin.2009.anie},
  relatedtype = {translatedas}
}

@article{Buntin.2008.anie,
  author = {Buntin, Kathrin},
  year = {2008},
  pages = {4595--4599},
  pagination = {page},
  volume = {47},
  journal = {Angew. Chem. Int. Ed.},
}

@article{Buntin.2009.ange,
  author = {Buntin, Kathrin},
  year = {2009},
  pages = {9957},
  pagination = {page},
  volume = {121},
  journal = {Angew. Chem.},
}

@article{Buntin.2009.anie,
  author = {Buntin, Kathrin},
  year = {2009},
  pages = {9773},
  pagination = {page},
  volume = {48},
  journal = {Angew. Chem. Int. Ed.},
}
\end{filecontents*}

\addbibresource{\jobname.bib}

\renewcommand*\relateddelim{\addsemicolon\addspace}

\begin{document}
  Cited.\autocite{Buntin.2008.ange}

  \printbibliography
\end{document}

Produces:

A: The standard styles used to have a structurally similar problem that was fixed in version 3.11 (https://github.com/plk/biblatex/pull/704/files). The \relateddelims should be printed with \printunit since the next \print... command might print nothing.
The same fix for chem-angew:
\documentclass{article}

\usepackage[backend=biber, style=chem-angew]{biblatex}

\RequirePackage{filecontents}
\begin{filecontents*}{\jobname.bib}
    @article{Buntin.2008.ange,
        author = {Buntin, Kathrin},
        year = {2008},
        pages = {4671--4676},
        pagination = {page},
        volume = {120},
        journal = {Angew. Chem.},
        related = {Buntin.2008.anie,Buntin.2009.ange,Buntin.2009.anie},
        relatedtype = {translatedas}
    }

    @article{Buntin.2008.anie,
        author = {Buntin, Kathrin},
        year = {2008},
        pages = {4595--4599},
        pagination = {page},
        volume = {47},
        journal = {Angew. Chem. Int. Ed.},
    }

    @article{Buntin.2009.ange,
        author = {Buntin, Kathrin},
        year = {2009},
        pages = {9957},
        pagination = {page},
        volume = {121},
        journal = {Angew. Chem.},
    }

    @article{Buntin.2009.anie,
        author = {Buntin, Kathrin},
        year = {2009},
        pages = {9773},
        pagination = {page},
        volume = {48},
        journal = {Angew. Chem. Int. Ed.},
    }
\end{filecontents*}

\addbibresource{\jobname.bib}

\renewcommand*\relateddelim{\addsemicolon\addspace}

\makeatletter
\renewbibmacro*{related}{%
  \ifboolexpr{
    not test {\iftoggle{bbx:related}}
    or
    test {\iffieldundef{related}}
  }
    {}
    {%
     \setunit{\addsemicolon\space}%
     \setcounter{bbx:relatedcount}{0}%
     \setcounter{bbx:relatedtotal}{0}%
     \def\do##1{\stepcounter{bbx:relatedtotal}}%
     \docsvfield{related}%
     \def\do{%
       \stepcounter{bbx:relatedcount}%
       \ifnumgreater{\value{bbx:relatedcount}}{1}
         {\printunit{\relateddelim}}
         {}}%
     \ifbibmacroundef{related:\strfield{relatedtype}}
       {\appto{\do}{\usebibmacro{related:default}}}
       {\appto{\do}{\usebibmacro*{related:\strfield{relatedtype}}}}%
     \iffieldformatundef{related:\strfield{relatedtype}}
       {\def\bbx@tempa{related}}
       {\def\bbx@tempa{related:\strfield{relatedtype}}}%
     \printtext[\bbx@tempa]{%
       \iffieldundef{relatedstring}
         {\ifboolexpr{
            test {\ifnumgreater{\value{bbx:relatedtotal}}{1}}
            and
            test {\ifbibxstring{\thefield{relatedtype}s}}
          }
            {\printtext{\bibstring{\thefield{relatedtype}s}\relatedpunct}}
            {\iffieldbibstring{relatedtype}
               {\printtext{\bibstring{\thefield{relatedtype}}\relatedpunct}}
               {}}}
         {\iffieldbibstring{relatedstring}
            {\printtext{\bibstring{\thefield{relatedstring}}\relatedpunct}}
            {\printtext{\printfield{relatedstring}\relatedpunct}}}%
       \docsvfield{related}}}}
\makeatletter

\begin{document}
    Cited.\autocite{Buntin.2008.ange}

    \printbibliography
\end{document}


text:
Q: Move the sprite on the direction of swipe I want to move my sprite(spaceship) in the direction of the swipe from the user.
ie,
move left - left swipe
move up - upward swipe etc..
I am new to swipe coding,so please help.

A: This will do :
 - (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event
{

    if (touchState != kSceneStateUngrabbed) return NO;

    // Store the starting touch point
    CGPoint touchPoint = [touch locationInView:[touch view]];
    startTouchPoint = touchPoint;

    touchPoint = [[CCDirector sharedDirector] convertToGL:touchPoint];

    // Change touch state
    touchState = kSceneStateGrabbed;

    return YES;
}

    - (void)ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event
    {
        CGPoint touchPoint = [touch locationInView:[touch view]];

        float rightleft = touchPoint.x-startTouchPoint.x ;
        float updown =  touchPoint.y-startTouchPoint.y;
        if(abs(rightleft)>abs(updown)){
            if(rightleft>0)
            {
                [ spaceShip runAction:[CCMoveTo actionWithDuration:1 position:ccp(winsize.width,     spaceShip.position.y)]];

                }
                else
                [ spaceShip runAction:[CCMoveTo actionWithDuration:1 position:ccp(0, spaceShip.position.y)]];
            }
        else{
                if(updown<0){
                [ spaceShip runAction:[CCMoveTo actionWithDuration:1 position:ccp(spaceShip.position.x, winsize.height)]];
                        }
                else
                [ spaceShip runAction:[CCMoveTo actionWithDuration:1 position:ccp(spaceShip.position.x, 0)]];

            }

    }

    - (void)ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event
    {
        // Change touch state
        touchState = kSceneStateUngrabbed;

    }


text:
Q: Dependency error trying to install gmodels package I have tried to install the gmodels package several ways in R Studio: Used:
Tools > Install Packages...

Downloaded the .gz file from

here
and I am still getting:
ERROR: dependency 'gdata' is not available for package 'gmodels'

EDIT:
I added the dependencies=TRUE and returned this error:
Warning in install.packages :
  installation of package 'C:/Users/Downloads/gmodels_2.15.4.1.tar.gz' had non-zero exit status

A: So you are on Windows (which wasn't obvious before) and you are downloading a tar.gz file which is a source file and you probably don't have the compiler Tools. If you are using the RStudio dropdown for "package archive" in the Install panel\, you should switch to the "Repository (CRAN)" selection so that RStudio will go and get the binary versions of the package.


text:
Q: Javascript object accessing it's properties I am trying to create an object in javascript that has an animation run which calls another method when it finishes.
function panel_manager() {
    this.animating = false;

    this.doAnimate = function (nPanel) {
        //if we're still moving panels, do nothing
        if(this.animating) return;

        this.animating = true;

        //enlarge new panel
        $("#panel" + this.focusedPanel).animate({width:"115px"},1000, this.endAnim);
    }

    this.endAnim = function () { alert("called"); this.animating = false; }
}

A whole lot has been cut for brevity and this code does work when it isn't inside an object and uses global variables. The alert runs, but animating isn't changing.

A: variables.
function panel_manager() {
    var that = this;
    this.animating = false;
    this.doAnimate = function (nPanel) {
        if(this.animating) return;
        this.animating = true;
        $("#panel" + this.focusedPanel).animate({width:"115px"},1000, that.endAnim);
    }
    this.endAnim = function () { alert("called"); that.animating = false; }
}

A: Inside of this.doAnimate add a $.proxy.
var callback = $.proxy( this.endAnim, this );

$("#panel" + this.focusedPanel).animate({width:"115px"},1000, callback);

Basically the problem is you lose your this value when you assign it to a callback like this. proxy will make sure the function is called with the proper this.
Cheers!


text:
Q: How to run JSONiq from JSON with try.zorba.io I need to write a JSONiq  expression that lists only the name of the products that cost at least 3. This is my JSON file which i had typed in the XQuery section:
{ "supermarket_visit":{
        "date":"08032019",
        "bought":[
            "item",{
                "type":"confectionary",
                "item_name":"Kit_Kat",
                "number": 3,
                "individual_price": 3.5
                },
            "item",{
                "type":"drinks",
                "item_name":"Coca_Cola",
                "number": 2,
                "individual_price": 3
                },
            "item",{
                "type":"fruits",
                "item_name":"apples",
                "number": "some"
                }
            ],
"next_visit":[
            "item",{
                "type":"stationary",
                "item_name":"A4_paper",
                "number": 1
                },
            "item",{
                "type":"stationary",
                "item_name":"pen",
                "number": 2
                }
            ]
        }
}

and this is my JSONiq Xquery JSONiq command, which i dont really know where to type in try.zorba.io:
let $x := find("supermarket_visit")
for $x in $supermarket.bought let $i := $x.item
where $i.individual_price <=3
return $i.item_name

I am getting many errors in try.zorba.io and im really new to JSONiq and JSON. Is something wrong with my JSON or JSONiq part?

A: The following selection works for me at the site you linked to:
jsoniq version "1.0";
{ "supermarket_visit":{
        "date":"08032019",
        "bought":[
            "item",{
                "type":"confectionary",
                "item_name":"Kit_Kat",
                "number": 3,
                "individual_price": 3.5
                },
            "item",{
                "type":"drinks",
                "item_name":"Coca_Cola",
                "number": 2,
                "individual_price": 3
                },
            "item",{
                "type":"fruits",
                "item_name":"apples",
                "number": "some"
                }
            ],
"next_visit":[
            "item",{
                "type":"stationary",
                "item_name":"A4_paper",
                "number": 1
                },
            "item",{
                "type":"stationary",
                "item_name":"pen",
                "number": 2
                }
            ]
        }
}.supermarket_visit.bought()[$$ instance of object and $$.individual_price le 3].item_name

A: The original query can be slightly modified to (in order to keep a FLWOR expression):
jsoniq version "1.0";

let $document := { (: put the document here :) }
for $x in $document.supermarket_visit.bought[]
where $x instance of object and $x.individual_price le 3
return $x.item_name

Note that try.zorba.io is an older version of Zorba (2.9) that does not implement the latest, stable JSONiq version. This is why () must be used instead of [] on this specific page. If you download the latest version of Zorba, the above query should work.
Also, the original document provided in the question is not well-formed JSON, because it contains a special em space character (Unicode 2003) on the line above "next_visit". This character must be removed for this JSON to be parsed successfully.


text:
Q: Characterizing finite convex combinations of ergodic probability measures Let $X$ be a topological space and $T: X \to X$ an invertible continuous map.
Recall that $T$ is ergodic with respect to a $T$-invariant probability measure $\mu$ if and only if any $T$-invariant function in the space $L^2(X, \mu)$ of square-integrable functions with respect to $\mu$ is constant almost everywhere.
Is there any simple property of this kind that characterizes when a $T$-invariant probability measure $\mu$ is a finite convex combination of ergodic probability measures?
A reference to any other characterizations of finite convex combinations of ergodic probability measures would also be appreciated.


text:
Q: How to assign type specific value on ref generic variable in C#? Let's imagine a generic method :
public void DoSomething<T>(ref T value) where T : struct
{
  if(value is float)
  {
    value = (T)0.5f;
  }
}

This doesn't work. Searching the internet, I found the solution to this is :
value = (T)(object) 0.5f;

I am just curious, since it's boxing and unboxing the value, isn't it allocating extra memory, which will need to garbage collected? Is there no other better way to assign the float value to the generic variable?

A: The compiler doesn't necessarily consider what will happen at run time. Your if statement will guarantee that, at run time, the line inside the if block will never be executed if T is not float but the compiler doesn't consider that. When it evaluates this line:
value = (T)0.5f;

all it cares about is whether that cast is valid for all T. It's not, so the code won't compile. In this case:
value = (T)(object) 0.5f;

the cast from float to object is valid and the cast from object to T is valid for all T so the code compiles. Note that this code fails to compile for the same reason:
public void DoSomething<T>(ref T value) where T : struct
{
    if (value is float)
    {
        value = (T)"Hello World";
    }
}

while this code does compile for the same reason:
public void DoSomething<T>(ref T value) where T : struct
{
    if (value is float)
    {
        value = (T)(object)"Hello World";
    }
}

Obviously that last snippet would throw an exception at run time but, as I said, the compiler doesn't consider all the potential execution paths and which ones can and can't happen at run time. Casting string as T is not valid while casting string as object and object as T both are.


text:
Q: Asking for the amount of questions the user got right out of 100 questions I am relativly new to Python. My code doesnt work and so far I am getting these errors messages. Below these error messages is my code.
Any feedback would be appreciated.
  File "<string>", line 14, in <module>
  File "<string>", line 5, in total `

import math

def total(correct_answers, NUMBER_OF_QUESTIONS):
    if correct_answers > NUMBER_OF_QUESTIONS:
        raise ValueError("Your total cannot be more than the number of questions.")
    return math.ceil(correct_answers / NUMBER_OF_QUESTIONS)
NUMBER_OF_QUESTIONS = 100

try:
    correct_answers = int(input("How many answers did you get right in the test? "))
except ValueError as err:
    print("Oh no, thats not a valid value!")
else:
    final_result = total(correct_answers, NUMBER_OF_QUESTIONS)
if final_result <= 50:
    print("I think you need to revise more.")
elif final_result <= 70 and final_result > 50:
    print("You did quite well! Why dont you try revise more to get a higher score!")
else:
    print("You did superb! Congrats!!!!")

A: The issue lies in total():
def total(correct_answers, NUMBER_OF_QUESTIONS):
    if correct_answers > NUMBER_OF_QUESTIONS:
        raise ValueError("Your total cannot be more than the number of questions.")
    return math.ceil(correct_answers / NUMBER_OF_QUESTIONS)

You're returning the ceiling of the number of correct answers divided by the number of questions. Meaning that if you got 50% of the answers correct, the result of the division is 0.5, and then you're using the ceiling to raise it to 1. Meaning that the function basically only ever returns 1.
In order for your code to work no matter what value NUMBER_OF_QUESTIONS has, you have a few options. One is to multiply the result of total() by 100 before applying ceil to it. Another is to just return the non-ceiling value and change the range of your if statements.
Here's the first way:
def total(correct_answers, NUMBER_OF_QUESTIONS):
    if correct_answers > NUMBER_OF_QUESTIONS:
        raise ValueError("Your total cannot be more than the number of questions.")
    return math.ceil(100 * correct_answers / NUMBER_OF_QUESTIONS)

And the second way:
import math

def total(correct_answers, NUMBER_OF_QUESTIONS):
    if correct_answers > NUMBER_OF_QUESTIONS:
        raise ValueError("Your total cannot be more than the number of questions.")
    return correct_answers / NUMBER_OF_QUESTIONS
NUMBER_OF_QUESTIONS = 100

try:
    correct_answers = int(input("How many answers did you get right in the test? "))
except ValueError as err:
    print("Oh no, thats not a valid value!")
else:
    final_result = total(correct_answers, NUMBER_OF_QUESTIONS)
if final_result <= 0.5:
    print("I think you need to revise more.")
elif final_result <= 0.7 and final_result > 0.5:
    print("You did quite well! Why dont you try revise more to get a higher score!")
else:
    print("You did superb! Congrats!!!!")

A: The Error you are facing is because even though the user did not insert a number, your code still performs the calculations.  A workaround would be as follows and which will keep the user trying to insert input in case the input was not integer:
while True:
    try:
        correct_answers = int(input("How many answers did you get right in the test? "))
        final_result = total(correct_answers, NUMBER_OF_QUESTIONS)
        if final_result <= 50:
            print("I think you need to revise more.")
        elif final_result <= 70 and final_result > 50 :
            print("You did quite well! Why dont you try revise more to get a higher score!")
        else:
            print("You did superb! Congrats!!!!")
    except ValueError as err:
        print("Oh no, thats not a valid value!")

A: Hi it's a small math error you've got:
return math.ceil(correct_answers / NUMBER_OF_QUESTIONS)

should be:
return math.ceil( (correct_answers / NUMBER_OF_QUESTIONS) * 100 )

A: In your case you don't need to do math.ceil. You can simply do this as follows
NUMBER_OF_QUESTIONS = 100
def total(correct_answers, NUMBER_OF_QUESTIONS):
    if correct_answers > NUMBER_OF_QUESTIONS:
        raise ValueError("Your total cannot be more than the number of questions.")
    return correct_answers / NUMBER_OF_QUESTIONS

try:
    correct_answers = int(input("How many answers did you get right in the test? "))
except ValueError as err:
    print("Oh no, thats not a valid value!")
else:
    final_result = total(correct_answers, NUMBER_OF_QUESTIONS)
if final_result <= 0.5:
    print("I think you need to revise more.")
elif final_result <= 0.7 and final_result > 0.5:
    print("You did quite well! Why dont you try revise more to get a higher score!")
else:
    print("You did superb! Congrats!!!!")


text:
Q: PHP. Конкатенация константы со строкой в определении константы Перепробовал много способов определить константу на основе другой. Ничего не выходит. Гугл и мануалы тоже особо не помогли.
class Config {
    const PROJ_ROOT = "/srv/www/htdocs/inet_shop/admin";
    const IMAGES_DIR = self::PROJ_ROOT . "/images"; // тут ошибка
    // ...
}

Запускаю через консоль тесты и выдаёт:
PHP Parse error:  syntax error, unexpected '.', expecting ',' or ';' in /srv/www/htdocs/inet_shop/admin/config.php on line 5

Почему?


text:
Q: Are homeomorphic representations isomorphic? Let $G$ be a finite group. Let $V_1, V_2$ be two finite-dimensional real representations. Suppose $f: V_1 \to V_2$ is a $G$-equivariant homeomorphism. Can one conclude that $V_1$ and $V_2$ are isomorphic representations?

A: This is a famous problem, originating in work of de Rham, and the answer turns out to be No. The lowest-dimensional examples of non-linear similarity, as it is called, are in dimension 6, and examples only exist if the group has order divisible by (but not equal to) 4. This article contains a summary of the subject:
Sylvain Cappell, Julius Shaneson, Mark Steinberger, Shmuel Weinberger, and James West. The classification of nonlinear similarities over ${\text{Z}}_{2^r}$, Bulletin of the American Mathematical Society 22 (1990).
Mark Steinberger wrote another short summary of the subject, available here: http://math.albany.edu/topics/steinberger/msteinbergerrsch.pdf.


text:
Q: Image upload stuck with blazor server and BlazorInputFile I have a problem while uploading images to an app with blazor server.
I am currently using BlazorInputFile because I am using .Net Core 3.1
When I try to upload a series of images (100 images of about 500 kb size) after a while the upload is interrupted and the image gets corrupted. When the image in the upload destination folder is interrupted, it is always like this:

So this is my code for upload images:
<InputFile id="fileInput112" OnChange="SelectFiles" hidden multiple accept=".jpg, .jpeg, .png" />

@code{

    private async void SelectFiles(IFileListEntry[] files)
    {
        var folderProductImage = "images/products/";

        foreach (var item in files)
        {
            await Task.Run(() => UploadProductImage(item, folderProductImage));
        }
    }

    private async Task UploadProductImage(IFileListEntry item, string destDirName)
    {
        string fileUploadPath = Path.Combine(destDirName, item.Name);

        using (FileStream writer = new FileStream(fileUploadPath, FileMode.Create, FileAccess.ReadWrite))
        {
            await item.Data.CopyToAsync(writer);
        }
    }
}


text:
Q: css font issue in internet explorer I am using following code in CSS to render fonts, but it is not working in IE

@font-face{font-family: BELOVED; src: url('font/BELOVED.TTF');}

any suggestions?

A: IE does not support TTF file format (updated March 2016).
Here is a tool to convert your TTF into EOT.

A: you're better off going to fontsquirrel.com and whipping up an @font-face kit so you get maximum cross-browser. paul irish also has a slick bulletproof cross-browser example of how to embed @font-face correctly.

A: it is easy to solve by
go to this link http://www.fontsquirrel.com/fontface/generator
upload your font
then download all files have different font formats which is supported for different browsers and use in your project. now it will work accurately in all browsers

A: IE unfortunately does not support TTF fonts, so you will need to use an EOT as well, supported types/browsers are

*

*Internet Explorer (all versions): EOT

*Safari (3.2+): TTF / OTF

*iPhone (3.1) SVG

*Chrome (all versions): SVG (TTF/OTF added 25th Jan 2010)

*Firefox (3.5+): TTF/OTF (.WOFF added 3.6)

*Opera (10+) TTF/OTF

I've had limited success with font-face, but I hope that helps.

A: The bad news:  IE doesn't support standard fonts in TTF format. (I'm constantly amazed how difficult IE is to work with)
The good news: IE does support an alternative font format called EOT. You'll need to provide the font in both formats and amend your CSS to specify them both.
@font-face {
    font-family: Beloved;
    src: url(/location/of/beloved.eot); /* IE */
    src: local(Beloved), url(/location/of/beloved.ttf) format("truetype"); /* non-IE */
}

In general, you should be able to convert your TTF fonts to EOT format without too many problems, but you may find some fonts are unconvertable. In that case, you're out of luck.
More details here: http://randsco.com/index.php/2009/07/04/p680


text:
Q: Show DE is closed Does anyone know how to deal with the following kind of question?

Here is the definition of Dynkin System:

Also definition of intersection-closed:

A: Let $F\in \mathscr{D}_E$, by definition, we have
$$F\cap E\in\mathscr{D} $$
and $E\in\mathscr{D}$.
Since $\mathscr{D}$ is a Dynkin system,  $E \setminus \big( E\cap F \big)\in \mathscr{D}$, that is,
$$F^c\cap E\in\mathscr{D} $$
thus $F^c\in\mathscr{D}_E$.
Q.E.D.


text:
Q: Find percentage of rows that meet a condition without rounding I'm trying to find the percentage of rows that meet a specific condition. My query is close but the answer is always rounded to the nearest whole number.
For instance this query below is returning 6 but it should return 6.25. Meaning 6.25% of the rows meet that condition. How would I do this?
select sum(case when name like 'H%' then 1 else 0 end) * 100 / count(*)
from category

A: Just add a decimal point:
select sum(case when name like 'H%' then 1.0 else 0 end) * 100 / count(*)
from category;

Postgres does integer division.
You can also express this using avg():
select avg(case when name like 'H%' then 100.0 else 0 end)
from category;

The decimal point is not needed.  Although Postgres does integer division of integers, it calculates average of integers using decimal points.
And this can be phrase more simply (assuming that name is not NULL):
select avg( (name like 'H%')::int ) * 100
from category;

A: You need a decimal value, otherwise, since both the numerator and denominator are integers, Postgres does integer division.
But here, I would just use avg() - for which you don't need an integer value:
select avg(case when name like 'H%' then 1 else 0 end) * 100
from category

A: You're performing integer division, and thus omitting everything right of the decimal point. If you use a floating-point literal 100.0, you should be OK:
select sum(case when name like 'H%' then 1 else 0 end) * 100.0 / count(*)
from category


text:
Q: mysql open hours past midnight I'm building a api where i have a list of drinking bars that are open past midnight.
I'm having problems finding out if they are currently open or closed.
Lets say for example that one of these bars has these opening hours:
Monday
open time = 20:00
closed time = 05:00

Tuesday
open time = 20:00
closed time = 04:00

If I want to know if a bar is currently open and the current time 04:00 (monday going on tuesday), this would result in that the current bar is closed because its tuesday and the closed time = 04:00
But what the actual result should be is that the bar is open until 05:00 (monday going on tuesday)
I have a list of 20+ bars where i need to know if they are currenly open or closed.
Can this be accomplished in mysql or php? how should I setup my db table?
I have this as my current setup
Table Name : openhours
Fields :
 id          int(11)
 bar_id      int(11)
 open_time   time
 close_time  time
 day         tinyint(1)

table records:
 id: 1
 bar_id: 1
 open_time: 20:00:00
 closed_time: 05:00:00
 day: 0

 id: 2
 bar_id: 1
 open_time: 20:00:00
 closed_time: 04:00:00
 day: 1

this query works fine for open days that dont go past midnight
SELECT `open_time`, `closed_time`, IF(CURTIME() BETWEEN `open_time`
AND `closed_time`,'open','closed') AS `status` FROM `openhours`
WHERE `day` = DATE_FORMAT(NOW(), '%w')

But how do i go about the past midnight issue?
it tried something like this but it is not quite right
  SELECT open_time, close_time, day, (CASE WHEN ((open_time <= close_time
  AND open_time <= CURTIME() AND close_time >= CURTIME()) OR (open_time >= close_time
  AND (CURTIME() <= close_time OR CURTIME() >= open_time))) THEN 'open' ELSE 'closed'
  END) AS status FROM openhours WHERE bar_id = 2 and CASE WHEN (day = WEEKDAY(NOW())
  AND (CURTIME() < open_time)) THEN CASE WHEN (day = (WEEKDAY(NOW()) - 1)
  AND (CURTIME() < close_time)) THEN day = (WEEKDAY(NOW()) - 1)
  ELSE day = WEEKDAY(NOW()) END ELSE day = WEEKDAY(NOW()) END

Thanks in advance!

A: You can use UNIX_TIMESTAMP() for this kind of issues:
SELECT `open_time`, `closed_time`, IF(UNIX_TIMESTAMP(CURTIME()) BETWEEN UNIX_TIMESTAMP(`open_time`) AND UNIX_TIMESTAMP(`closed_time`),'open','closed') AS `status` FROM `openhours` WHERE `day` = DATE_FORMAT(NOW(), '%w')

I hope I get your point :)

A: You want something like this
case closed < open
 not between open and closed
else
 between open and closed

When either return true, the bar is open

A: One option would be to store the seconds past the start of the week, that way you don't need to worry about midnight at all.
Add these to your table:
open_time_i   int(11)
closed_time_i int(11)

And make your data look like this:
id: 1
bar_id: 1
open_time: 20:00:00
open_time_i: 72000
closed_time: 05:00:00
closed_time_i: 104400
day: 0

id: 2
bar_id: 1
open_time: 20:00:00
open_time_i: 158400
closed_time: 04:00:00
closed_time_i: 187200
day: 1

Then your lookup could look like:
$seconds = time() - strtotime('this week last sunday', date("Y-m-d", time()))

SELECT `open_time`, `closed_time`, IF(
  $seconds BETWEEN `open_time_i` AND `closed_time_i`
    OR
  (("closed_time_i" >= 604800 AND $seconds BETWEEN 0 AND ("closed_time_i" - 604800)))
,'open','closed') AS `status` FROM `openhours`

The 2nd between statement checks if the bar was open past that change of week.


text:
Q: Eureka TextAreaRow inputting content covered by keyboard I add lots of Rows to my FormViewController,Second from the top is TextAreaRow.
textAreaRow = TextAreaRow(){row in
    row.textAreaHeight = TextAreaHeight.dynamic(initialTextViewHeight: 30)
    row.placeholder = "..."
}

But when I keep inputting something in textAreaRow, the inputed content is covered by keyboard (Demo GIF in below):

You can see in the demo ,when I input 5 and go on,it's covered by keyboard.
How to fix it???
Could I scroll textAeraRow when it's covered by keyboard?How to do that???
thanks :)

A: An easy fix for this is on the onChange event of the TextAreaRow
.onChange({ [weak self] row in
      self?.view.layoutIfNeeded() //or self?.tableView.layoutIfNeeded()
})


text:
Q: MySql master slave replication in Windows Server I was referring this link to perform MySql master slave replication for a particular mysql database in my Windows server.
Its mentioned to write the following configuration in the my.ini file.
log-bin = /var/log/mysql/mysql-bin.log
binlog-do-db=exampledb
server-id=1

Since I am using a windows server I cannot use the above path for the log-bin attribute. So which is the log-bin path for mysql running in a windows server?
Thanks

A: If you did not change your default data path (I am assuming this the case based on your post) then your path would look something like this
log-bin ="C:\ProgramData\MySQL\MySQL Server 5.6\mysql-bin.log"
If you are running version 5.5 it would look like this:
log-bin="C:\ProgramData\MySQL\MySQL Server 5.5\mysql-bin.log"

The key thing to remember here is that MySQL has to have permission to write the logs to wherever you are writing them to.
You could even create another folder and call it log within the MySQL folder. The path would look like this:
log-bin ="C:\ProgramData\MySQL\MySQL Server 5.6\log\mysql-bin.log"
Just as a side note: you should really consider looking at how mysql is installed on your windows server before going into more complex things like master-slave replication...

A: For windows systems, you can use something like
log-bin = "F:/mysql/mysql-bin.log"

Which path you're using actually doesn't really matter too much, but keep in mind the MySQL needs write permissions for it. P.e., for backuping reasons I'd like it to stay close to my MySQL installation data directory.