text:
Q: Map mouse position to 3d plane's coordinate system Using OpenGL with an orthographic projection.
I've defined a plane in 3d. Its position and orientation are defined by a 4x4
matrix.
What I'd like to be able to do is sketch, with the mouse, in the plane.
I can find the intersection with the plane by casting a ray from the mouse
into the screen. This point is in reference to the world coordinate system
(OpenGL's identity modelview matrix) x+ right, y+ up, z+ out of the screen.
I've found a lot of examples of this, intersect a ray with a plane.
Now, how do I map that point to the plane's coordinate system? This has probably been answered in a related question but I can't seem to find it.

A: One way to define plane is by two non-colinear vectors and a base point.
p(u,v) = ↑r + u·↑a + v·↑b, where u,v are scalars

After doing the plane ray intersection you know the point of intersection with the plane ↑h, which by definition must lie on the plane. To get the values of u,v for that point you have to project the vector from ↑r to the intersection point onto the base vectors ↑a and ↑b:
u = (↑h - ↑r) · ↑a ; where '·' denotes the scalar product
v = (↑h - ↑r) · ↑b


text:
Q: Website only shows ip address, not domain name I'm trying to set up a website on a home server with joomla. I've managed to set up correct forwarding so it is accessible via my IP address, and I have purchased a domain name from a hosting provider. I set up the DNS settings to point my domain name to my IP address, but any request to the domain name first gets routed to a different IP address, which sends back a 301 response, with my IP as the new target. I then end op on my website with the plain IP address in the address bar.
Now I have very limited experience with DNS, but this seems wrong? In googling for the issue I mostly get results about this being a joomla and/or apache issue and get pointed to various config files, but I don't want to mess those up just yet unless I'm sure the problem doesn't lie anywhere else.
Could what I'm seeing with the 301 redirect be the cause of this issue or is it definitely on the server config side?

A: I think what you've set up wasn't the DNS record but an HTTP redirect (from a virtual host at your hoster).
If DNS is set correctly, an nslookup or dig should show an A record resolving the DNS name to the IP of your server. As it is, the A record likely points to the virtual host where your provider redirects the request.

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to gather Instruments memory/zombies data after removing & restarting app in the simulator? How can I gather Instruments memory/zombies data after removing app in simulator and restarting in simulator?
What I see in the simulator after I remove the app process, and then retart it by clicking on it's icon in the simulator, is that Instruments has stopped receiving the data from the application?
Background

*

*I'm trying to test saving and loading data via NSUserDefaults.  After saving it to test the loading part I need to simulate removing the app from memory, so what I have been doing is manually removing the app process on the simulator (double click on menu button etc).

*What I'm finding is that when I do run up the app this way there is some problem at start up - getting "Thread 1 - Program received signal SIGKILL" against the " int retVal = UIApplicationMain(argc, argv, nil, nil);" line of code

*Therefore I thought I would try to run in Instruments to track down the issue, hence my question as Instruments seems to "stop recording" after I kill the app process on the simulator and then restart.

A: Not possible (i.e. no answers yet so I'm guessing the correct answer may be that it's not possible)


text:
Q: Подскажите пожалуйста как в laravel правильно залогинится чтоб он видел в база данных, если логин равно login, а пароль равно passwors. Спасибо $data = new userModel();
$data->email = $r->email;
$data->password = Hash::make($r->password);

A: Пользуйтесь стандартной аутентификацией Laravel.
Сделайте все как указано в инструкции и все будет работать!
https://laravel.su/docs/6.x/authentication
Не придумывайте велосипед!)


text:
Q: Error Activating SharePoint Server Publishing Infrastructure on SharePoint Online I am failing to enable the Publishing Infrastructure feature on SharePoint Online.  I am getting the following error:

Sorry, something went wrong
  A duplicate field name "PublishedLinksDisplayName" was found.
  Technical Details
Troubleshoot issues with Microsoft SharePoint Foundation.
  Correlation ID: 7255fa9c-0008-1000-cd28-117709c7ac79
  Date and Time: 07/04/2015 02:16:04

A: Deactivate the feature and then try to reactivate it. It might solve the problem
To Deactivate
stsadm -o deactivatefeature -id f6924d36-2fa8-4f0b-b16d-06b7250180fa -url "<Site Collection URL>" -force

To Activate
stsadm -o activatefeature -id f6924d36-2fa8-4f0b-b16d-06b7250180fa -url "<Site Collection URL>" -force


text:
Q: Add three string and merge by "-" ruby I have three strings:
first  = "test"
second = "hello"
third  = "world"

I want to concatenate them like this:
test-hello-world

I tried using +:
first + "-" + second + "-" + third

But I'm looking for a better way to do this in Ruby.

A: You can do:
[first, second, third].join('-')
Or, if you don't care about variables:
%w(test hello world).join('-')

A: Try this:
[first, second, third].join('-')

A: If they were in an array, you could use .join
[first, second, third].join('-')


text:
Q: When to use OR and when to use AND in java I'm remediating some deference and redundant null findings and am just curious when someone should use an AND or an OR in a if statement.
One of the findings is at this if statement
String firstName = db.getString("FIRST_NAME");
if(!((firstName == null) || firstName.equals(""))){
...
}

Is using an OR or and AND (if(firstName != null && !firstName.equals(""))){}) more efficient? Or is it usually just a personal preference?
Also if someone could point out how that line has dereference that would be nice too

A: This is a micro-optimization that will have no effect on your code performance. JVM might do various optimizations with your code during runtime due to JIT e.g. inline the method. You should prefer whichever you find more readable, could be something like StringUtils.isNotEmpty.
The variable db implies that you are accessing the database which is orders of magnitude more expensive than simple comparisons. More or less:
Latency Comparison Numbers
--------------------------
L1 cache reference                           0.5 ns
Branch mispredict                            5   ns
L2 cache reference                           7   ns                      14x L1 cache
Mutex lock/unlock                           25   ns
Main memory reference                      100   ns                      20x L2 cache, 200x L1 cache
Compress 1K bytes with Zippy             3,000   ns        3 us
Send 1K bytes over 1 Gbps network       10,000   ns       10 us
Read 4K randomly from SSD*             150,000   ns      150 us          ~1GB/sec SSD
Read 1 MB sequentially from memory     250,000   ns      250 us
Round trip within same datacenter      500,000   ns      500 us
Read 1 MB sequentially from SSD*     1,000,000   ns    1,000 us    1 ms  ~1GB/sec SSD, 4X memory
Disk seek                           10,000,000   ns   10,000 us   10 ms  20x datacenter roundtrip
Read 1 MB sequentially from disk    20,000,000   ns   20,000 us   20 ms  80x memory, 20X SSD
Send packet CA->Netherlands->CA    150,000,000   ns  150,000 us  150 ms

A: Personal preference.  How these 2 statements are translated into byte code and executed in the runtime environment are subject to change.  Any performance difference you would get will likely be negligible.
You didn't ask this directly, but this is an example of De Morgan's laws.


text:
Q: Finding a sphere tangent to 3 other spheres So it's been a long time I didn't practice and I find myself stuck with that problem...
I have three spheres, of known position and radius. I'm looking to find the position of a 4th sphere (of known radius), so it is tangent to the first three spheres.
I just have no clue of where to start. Any help would be much appreciated!


text:
Q: How to change local address in fetch API React I have a local API which is hosted in http://127.0.0.1:8080 and React server is in http://127.0.0.1:5500. I want to design a user interface for the API by a React webpage. But React puts its local address in front of the Get Api like http://127.0.0.1:5500/public/127.0.0.1:8080/lst/users. Even if I just put /lst/users in the fetch method address and define a proxy "proxy": "http://127.0.0.1:8080" in the app.json, the React will try to get http://127.0.0.1:5500/lst/users. How should I fix this.
// get all entities - GET
fetch('127.0.0.1:8080/lst/users', {
  "method": "GET",
  mode:'no-cors',
  url:'http://127.0.0.1:8080',
  credentials:'include'

})
.then(response => response.json())
.then(response => {
  this.setState({
    friends: response
  })
})
.catch(err => { console.log(err);
});

A: You need to add the protocol else it will be treated as relative path.
add "http" => http://127.0.0.1:8080
E.g.
fetch('http://127.0.0.1:8080/lst/users', {
  "method": "GET",
  mode:'no-cors',
  credentials:'include'

})
.then(response => response.json())
.then(response => {
  this.setState({
    friends: response
  })
})
.catch(err => { console.log(err);
});


text:
Q: Pushing a file to GitLab with Maven I'm trying to push a file, the index.md from the markdown folder to my project stored in GitLab, I'm using Maven, but I don't know if it's possible to select just a single file to push it to GitLab.
Thank you.

A: Go to project folder and do that in your command in line terminal:
$ git add index.md

if it don't work do that :
$ git add -f index.md

where -f means forced
Then :
$ git commit -m index.md
$ git push


text:
Q: Bot keeps crashing when wrong command is sent. [Discord JS] I'm trying to make an Arby's Bot. Whenever someone sends a message in the channel, the bot crashes and bot doesn't work.
client.on("message", (message) => {
  if (message.content.startsWith("arbys") || message.guild.channel == message.guild.channels.cache.get("843008525335920651")) {
  } else
    setTimeout(() => message.delete(), 1);
  message.author.send("**arbys** Only Arbys. GOT IT?")
});

If someone could please help me that would be amazing.

A: message.guild doesn't have a channel property, but that's not the only problem. You can't compare an object (message.guild.channel) to another object (message.guild.channels.cache.get("843008525335920651")) like that. You can, however, check if the channel the message is sent in has the same ID as you want (843008525335920651).
You can also delete the message after you sent a DM to the message author using the .then() method. Check out the code below:
client.on('message', (message) => {
  if (
    message.content.startsWith('arbys') ||
    message.channel.id === '843008525335920651'
  ) {
    // do something ?
    console.log('Correct channel or command');
  } else {
    // send a DM to the author
    message.author
      .send('**arbys** Only Arbys. GOT IT?')
      // and delete the original message
      .then(() => message.delete())
      // catch them errors :)
      .catch((error) => console.log(error));
  }
});

A: its because message.guild does not have a channel property, instead do this
if (message.content.startsWith("arbys") || message.channel.id == "843008525335920651"){
hope this helped >:D


text:
Q: Consumir Api Rest - PHP Buenos días comunidad!
En una web que tengo (en PHP) deseo enviar archivos hacia otro sistema, dicho sistema me provee una api para realizar la acción deseada.
Mediante los diferentes endpoint que me provee la api pude traer datos de carpetas, tipos de documentos y entre otras cosas particulares de ese sistema. Todo esto utilizando file_get_contents().
Bien, de momento solo he realizado peticiones tipo GET, ahora necesito realizar la de tipo POST, para enviar un archivo. En este caso, la api ademas de tener que darle valores al endpoint me pide un body, es una estructura json la cual ya la arme. Esta estructura body la arme como el siguiente estilo:
                $body = [
                "file"   => $archivo_en64,
                "fileds" => array(
                    [
                        "DocumentTypeId" => $tipo_documento,
                        "DocumentId"     => 0,
                    ],
                ),
                "properties" => array(
                    [
                        "Id"             => "25",
                        "DisplayName"    => "IDTIPODOC",
                        "DefaultValue"   => array(
                            25
                        )
                    ],
                    [
                        "DisplayName"    => "NAME",
                        "DefaultValue"   => array(
                            "Gus desde Demo"
                        )
                    ],
                    [
                        "DisplayName"    => "FROMATO",
                        "DefaultValue"   => array(
                            ".TXT"
                        )
                    ]
                ),
                "policies" => null
            ];

Esta estructura deberia hacerle un json_encode?
Ahora el metodo que encontre para realizar el POST a la api es mediante curl. De momento arme esto:
$ch = curl_init($crear_archivo);

            //setup request to send json via POST

            //attach encoded JSON string to the POST fields
            curl_setopt($ch, CURLOPT_POSTFIELDS, $body_enconded);

            //set the content type to application/json
            curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));

            //return response instead of outputting
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

            //execute the POST request
            $result = curl_exec($ch);
            echo $result;
            //close cURL resource
            curl_close($ch);

Pero no me funciona.
Agradeceria si me podrian ayudar con esto.
Gracias!


text:
Q: selecting space in between Emails I am using MySQL I have a table called Associations where there is a column called Email
Emails are in format
abc@xyz.com
if I want to select all emails which have word webmaster I use query.
 select * from associations where email like '%webmaster%';

there are some emails which has space and are not in format abc.xyz.com
they are in format like
 @abc. xyxyz . com
how can i select all emails that have space in between them.

A: You can use like:
where email like '% %'

To get a lot of bad format emails, you could do:
where email like '% %' or
      email not like '%@%.%'

A: If you wanted to find emails that have any sort of whitespace in them (e.g., spaces, tabs, etc.), then you might want to use the following:
SELECT * FROM associations
 WHERE email RLIKE '\s'

One caveat is that matching regular expressions is a heavy CPU operation.


text:
Q: Error when drawing route between two GeoPoints on Android MapView? I am using this method to draw route between two points on map in my application
 private void DrawPath(GeoPoint src, GeoPoint dest, int color,
          MapView mMapView01) {

        // connect to map web service
        StringBuilder urlString = new StringBuilder();
        urlString.append("http://maps.google.com/maps?f=d&hl=en");
        urlString.append("&saddr=");//from
        urlString.append( Double.toString((double)src.getLatitudeE6()/1.0E6 ));
        urlString.append(",");
        urlString.append( Double.toString((double)src.getLongitudeE6()/1.0E6 ));
        urlString.append("&daddr=");//to
        urlString.append( Double.toString((double)dest.getLatitudeE6()/1.0E6 ));
        urlString.append(",");
        urlString.append( Double.toString((double)dest.getLongitudeE6()/1.0E6 ));
        urlString.append("&ie=UTF8&0&om=0&output=kml");
        Log.d("xxx","URL="+urlString.toString());

        try
        {
          URL url = new URL(urlString.toString());
          urlString = null;
          HttpURLConnection urlConnection=(HttpURLConnection)url.openConnection();
          urlConnection.setRequestMethod("GET");
          urlConnection.setDoOutput(true);
          urlConnection.setDoInput(true);
          urlConnection.connect();

          DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
          DocumentBuilder db = dbf.newDocumentBuilder();
          Document doc = db.parse(urlConnection.getInputStream());

          if(doc.getElementsByTagName("GeometryCollection").getLength()>0)
          {

            String path = doc.getElementsByTagName("GeometryCollection").item(0).getFirstChild().getFirstChild().getFirstChild().getNodeValue() ;
            Log.d("xxx","path="+ path);
            String [] pairs = path.split(" ");
            String[] lngLat = pairs[0].split(","); // lngLat[0]=longitude lngLat[1]=latitude lngLat[2]=height
            // src
            GeoPoint startGP = new GeoPoint((int)(Double.parseDouble(lngLat[1])*1E6),(int)(Double.parseDouble(lngLat[0])*1E6));

            GeoPoint gp1;
            GeoPoint gp2 = startGP;

            for(int i=1;i<pairs.length;i++) // the last one would be crash
            {
              lngLat = pairs[i].split(",");
              gp1 = gp2;
              // watch out! For GeoPoint, first:latitude, second:longitude
              gp2 = new GeoPoint((int)(Double.parseDouble(lngLat[1])*1E6),(int)(Double.parseDouble(lngLat[0])*1E6));

              mapRouteOverlay = new MapRouteOverlay(gp1,gp2,2,color);

              mMapView01.getOverlays().add(mapRouteOverlay);
              Log.d("xxx","pair:" + pairs[i]);
              Log.e("Check  ","Draw  " + mapRouteOverlay);
            }

          }
        }
        catch (MalformedURLException e)
        {
          e.printStackTrace();
        }
        catch (IOException e)
        {
          e.printStackTrace();
        }
        catch (ParserConfigurationException e)
        {
          e.printStackTrace();
        }
        catch (SAXException e)
        {
          e.printStackTrace();
        }

      }

this method is working fine(from last three months) to draw path but form about 15 days it gives problem and not showing/drawing path.
my logcat output is
 08-11 10:15:47.363: W/System.err(401): org.xml.sax.SAXParseException: unterminated entity ref (position:ENTITY_REF &@1:808 in java.io.InputStreamReader@44f9cde8)
 08-11 10:15:47.373: W/System.err(401):     at org.apache.harmony.xml.parsers.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:153)
 08-11 10:15:47.373: W/System.err(401):     at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:110)
 08-11 10:15:47.373: W/System.err(401):     at com.map.MapMainActivity.DrawPath(MapMainActivity.java:621)
 08-11 10:15:47.373: W/System.err(401):     at com.map.MapMainActivity.getDirection(MapMainActivity.java:582)
 08-11 10:15:47.373: W/System.err(401):     at com.map.MapMainActivity$DownloadWebPageTask.onPostExecute(MapMainActivity.java:1318)
 08-11 10:15:47.373: W/System.err(401):     at com.map.MapMainActivity$DownloadWebPageTask.onPostExecute(MapMainActivity.java:1)
 08-11 10:15:47.373: W/System.err(401):     at android.os.AsyncTask.finish(AsyncTask.java:417)
 08-11 10:15:47.373: W/System.err(401):     at android.os.AsyncTask.access$300(AsyncTask.java:127)
 08-11 10:15:47.373: W/System.err(401):     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:429)
 08-11 10:15:47.373: W/System.err(401):     at android.os.Handler.dispatchMessage(Handler.java:99)
 08-11 10:15:47.373: W/System.err(401):     at android.os.Looper.loop(Looper.java:123)
 08-11 10:15:47.383: W/System.err(401):     at android.app.ActivityThread.main(ActivityThread.java:4627)
 08-11 10:15:47.383: W/System.err(401):     at java.lang.reflect.Method.invokeNative(Native Method)
 08-11 10:15:47.383: W/System.err(401):     at java.lang.reflect.Method.invoke(Method.java:521)
 08-11 10:15:47.383: W/System.err(401):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
 08-11 10:15:47.383: W/System.err(401):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
 08-11 10:15:47.383: W/System.err(401):     at dalvik.system.NativeStart.main(Native Method)

I could not understand what is the problem?
any help?
Thanks in Advance.

A: see this link definitely help you.
because the Google Directions from Google by parsing the KML file is no longer available since 27 July 2012 (because Google has changed the structure of retrieving Google Directions, now you can only get it by JSON or XML), it is time to migrate your code to JSON instead of KML.

A: If your purpose is only to draw the path between two geo-points then you can use android internal map activity.It easy and no overhead of having error.
String uri = "http://maps.google.com/maps?saddr=" + currentLatitude+","+currentLongitude+"&daddr="+fixedLatitude+","+fixedLongitude;
Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse(uri));
intent.setClassName("com.google.android.apps.maps", "com.google.android.maps.MapsActivity");
startActivity(intent);

A: Well, according to the Exception there is an error (unterminated entity ref) in some XML you are reading. I guess the points you want to draw are read from that XML and obviously there's an error in that XML (since those about 15 days probably).
Open the XML in an editor if that's possible and look for a <ref> with no matching </ref>.
Then you have two options:

*

*Fix the problem in program generating the XML

*Try to catch the SAXParserException in your App and skip the errornous point.


text:
Q: Qt under Ubuntu - typing accents Users of my application report, that they cannot use Dead Keys for typing accent characters in Brazilian Portuguese. The application is open source (SQLiteStudio) and I distribute it (precompiled packages) together with Qt libraries (dynamically linked).
This was tested with Qt 5.12.2 and Ubuntu 20.04.
I managed to reproduce it by doing following:

*

*I have a usual US-layout keyboard

*Install Ubuntu on VirtualBox

*Choose "Portuguese (Brazil)" keyboard from settings

*To confirm it works in general - I hit ; in any application and I get "ç", as expected. This one works also in my app.

*Try typing characters using "dead keys" in pre-installed Ubuntu apps (Terminal, Writer, etc), like:

*

*ḉ (by holding AltGr and hitting ;, followed by hitting ; once more, but without AltGr)

*ã (by typing ' and then a)

*Try typing the same characters using "dead keys" in my Qt application.

These combinations simply do not work. Instead of "ḉ" I get just "ç" and instead of "ã" I get just "a".
What am I doing wrong? Or what am I missing to do?


text:
Q: MySQL using Brew results in "Access denied" error I was able to successfully install MySQL using Brew. The server is started successfully also. I removed the password in the database table user for both root and Nora (my user). However, when I try to connect I get the message access denied.
mysqladmin shutdown
mysqladmin: connect to server at 'localhost' failed
error: 'Access denied for user 'Nora'@'localhost' (using password: NO)'

Now when I try to enter any password in phpmyyadmin the below message displays:
        #2002 - Socket operation on non-socket — The server is not responding
        (or the local server's socket is not correctly configured).

Though I have copied mysql.sock as below:
   sudo ln -s /tmp/mysql.sock /var/mysql/mysql.sock

But the only strange thing is that I found mysql.sock with LOCK refix. mysql.sock.lock. but I copied it manually anyway, could that be the root cause?

A: in the End, I was able to log in using root without password. However, that was not the issue, the issue was with the socket location and the host name.
1- I deleted the auto-created file mysql.sock.lock.
2- I changed the location in mysql configuration using the below command:
mysql_config_editor -v set --socket=/tmp/mysql.sock

3- I change the config file in phpMyAdmin as below: (changed the password rule to accept no password, host from localhost to 127.0.0.1 and socket location)
$cfg['Servers'][$i]['host'] = '127.0.0.1';
$cfg['Servers'][$i]['connect_type'] = 'tcp';
$cfg['Servers'][$i]['compress'] = false;
$cfg['Servers'][$i]['AllowNoPassword'] = fale;
$cfg['Servers'][$i]['socket']='~/Privare/tmp/mysql.sock';

I hope my solution make it to anyone who has faced similar issue :)


text:
Q: Tapping to cancel a Download I want to do the following:
1)DownLoad a series of files whose URLs are stored in an NSMutableArray.
2)During the download process a MBProgressHUD shows the download status.
3)At any point of download I want to cancel the download, when the user touches the screen.
-(void)singleTap:(UITapGestureRecognizer*)sender
{
NSLog(@"%@",@"tapped");
self.downLoadHud.detailsLabelText=@"";
self.downLoadHud.labelText=[SAGlobal stringForValue:@"CANCELLINGDOWNLOAD"];
SharedAppDelegatee.downLoadCancelFlag=YES;

}

-(void) startFileDownLoadingWithHUD
{

self.downLoadHud=[MBProgressHUD showHUDAddedTo:[SharedAppDelegatee window] animated:YES];
self.downLoadHud.mode = MBProgressHUDModeIndeterminate;
UITapGestureRecognizer *HUDSingleTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(singleTap:)];
[self.downLoadHud addGestureRecognizer:HUDSingleTap];
self.downLoadHud.labelText = @"Initialising..";
self.downLoadHud.detailsLabelText =@"";
[self.downLoadHud setColor:[UIColor blackColor]];
dispatch_queue_t dispatchQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);
dispatch_async(dispatchQueue, ^(void)
{

    [self startAllFilesInArrayDownload];
    //downloadcancelled or downloadfinished
    while (!(SharedAppDelegatee.downLoadCancelFlag)||(SharedAppDelegatee.SAdownloadMode==0)) {

         self.downLoadHud.labelText =[NSString stringWithFormat:@"Downloading..[%d/%d]",self.self.downloadErrorCount+self.downloadSuccessCount,[filesToDownLoad count]];
          self.downLoadHud.detailsLabelText =[SAGlobal stringForValue:@"TAPTOCANCEL"];
        //NSLog(@"DOWNLOADING------+");
    }
    ////////////////////////////////
    dispatch_sync(dispatch_get_main_queue(), ^{
        [self.downLoadHud hide:YES];
        //downLoadHud
    });
});

}
The download is done with
for (downDict in filesToDownLoad)
{
    //[adm downloadURL:[downDict objectForKey:@"url"]  destPath:[downDict objectForKey:@"toFile"]];
    NSURL *aUrl = [NSURL URLWithString:[downDict objectForKey:@"url"]];
    [self.downloadManager addDownloadWithFilename:[downDict objectForKey:@"toFile"] URL:aUrl];
    //[urlStringsArray addObject:[downDict objectForKey:@"url"]];
}

The "downloadManager" is an object of class "DownloadManager" which is obtained
https://github.com/robertmryan/download-manager
I could succesively download all files. I am NOT able to cancel the download in the middle of download. When the user taps the button, it waits a long time, and after some time, the  "singleTap" method is called.
The number of files downloaded and failed are CORRECTLY shown. What is wrong with my code?. Can any one suggest me a better example or way to handle "Showing a busy hud + downloading+ tap to cancel feature similar as shown below.

A: While I am certain that this is a great utility and a lot of work went into it I was immediately concerned when i saw that the repo was two years old.
These types of things are a great help and i can't begin to express my appreciation for the authors and their generosity in sharing so much hard work.  Unfortunately, if they are not maintained then they can become difficult for the user to update.
Apple has more recently introduced new functionality with NSURLSession.
This is pretty easy to use and is much more powerful than NSURLConnection.
It specifically includes the ability to pause, resume and cancel network downloads.


text:
Q: outputPanel not rerendered does someone has an idea, why the outputpanel "timeline" is not rerendered?
<apex:inputCheckbox id="budget" value="{!opp.Budget_available__c}" />
<apex:actionSupport event="onclick" rerender="pr, timeline" action="{!countPr}"/>
<apex:outputLabel for="budget" value="Customer has definded budget" />
<apex:outputPanel id="timeline">
<apex:outputPanel style="margin-left:3px;" rendered="{!IF(opp.Budget_available__c, 'true', 'false')}">
           Timeline: <apex:inputField value="{!opp.Timeline__c}" />
</apex:outputPanel>
</apex:outputPanel>

A: While the expression IF(opp.Budget_available__c, 'true', 'false') could be replaced with the simpler opp.Budget_available__c either will work.
Presumably opp.Budget_available__c is false initially. Are you assuming that when the budget checkbox is changed that the timeline label will render? That will only happen if you add:
<apex:inputCheckbox id="budget" value="{!opp.Budget_available__c}">
    <apex:actionSupport event="onchange" rerender="timeline"/>
</apex:inputCheckbox>

More explanation in Rendering section if checkbox is unchecked.


text:
Q: Saving an Excel file via OLE automation forces a password I create, fill and save an Excel file via OLE automation in Delphi.
When saving it, a password is automatically added to the file ("0").
FexclplctnXLApp.ActiveWorkbook.SaveAs(
    FAvailSaveName, xlWorkbookDefault,
    varEmpty,varEmpty, varEmpty, varEmpty, varEmpty, varEmpty,
    varEmpty, varEmpty, varEmpty, varEmpty, lcid);

VarEmpty seems to be the issue here, it's value is "0".
I tried also with '', with the same result.

A: The right parameter is EmptyParam. You need to specify an 'empty' variant for optional parameters that you don't want to give a value. You could use any variant for that, but EmptyParam is declared globally as an empty variant for this purpose.
You are using varEmpty, which is a numeric constant representing the type of such an empty variant. varEmpty indeed has the value 0, which, for a password will be interpreted as a string. See varEmpty constant.


text:
Q: How to zoom only content of RecyclerView I have a custom RecyclerView that zooms, but when I zoom in, the entire RecyclerView zooms in and I cannot scroll to the borders of the view because they are off the screen. How do I only zoom the content of the view and not the view itself?
Code for ZoomRecyclerView:
public class ZoomRecyclerView extends RecyclerView {
private ScaleGestureDetector scaleGestureDetector;
private static final String TAG = ZoomRecyclerView.class.getSimpleName();

private float scaleFactor = 1.f;
private static final float minScale = 1.0f;
private static final float maxScale = 3.0f;

public ZoomRecyclerView(Context context, AttributeSet attrs) {
    super(context, attrs);
    scaleGestureDetector = new ScaleGestureDetector(getContext(), new ScaleGestureDetector.OnScaleGestureListener() {
        @Override
        public boolean onScale(ScaleGestureDetector detector) {
            scaleFactor *= detector.getScaleFactor();

            //makes sure user does not zoom in or out past a certain amount
            scaleFactor = Math.max(minScale, Math.min(scaleFactor, maxScale));

            //refresh the view and compute the size of the view in the screen
            invalidate();

            return true;
        }

        @Override
        public boolean onScaleBegin(ScaleGestureDetector detector) {
            return true;
        }

        @Override
        public void onScaleEnd(ScaleGestureDetector detector) {
        }
    });
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    super.onTouchEvent(event);

    //notify the scaleGestureDetector that an event has happened
    scaleGestureDetector.onTouchEvent(event);

    return true;
}

@Override
protected void dispatchDraw(@NonNull Canvas canvas) {
    //scales the display, centered on where the user is touching the display
    canvas.scale(scaleFactor, scaleFactor, scaleGestureDetector.getFocusX(), scaleGestureDetector.getFocusY());

    super.dispatchDraw(canvas);
}
}


text:
Q: How to install an older version of HDF5 in ubuntu 18.04 I need HDF5 1.8.12 specifically on my machine.
How can I install this particular version on it? There doesn't seem to be an option to do so using apt-get.
Can I just download it from here and copy/merge the folders to my /usr/ ?


text:
Q: Mac internal/boot HD - "the disk you inserted is not readable by this computer" My iMac has been playing up and I thought it was the system, but then it froze completely and I had to force quit. When I restarted it booted in to an external drive that has its own system, but my main HD won't mount with the message "the disk you inserted is not readable by this computer". Ouch.
Considering it will still spin (I've removed it and put it on a SATA USB connector) what software options are recommended for recovery and what should I expect? There are a lot of options out there but any recommended that aren't too expensive? Do they just recover fragments or a mess of files? Its a Seagate SATA drive 3TB I installed in 2016.

A: I've used Data Rescue before: https://www.prosofteng.com
You'll get a big load of files, without hierarchy or filenames.
Note for the future: you can buy a backup disk for less than most data recovery software costs.


text:
Q: Create Google Extension that can process with Python Halo, I need to develop a Google extension that able to link with python. I already write the process code in the python, all I need is a extension that can scrape the Twitter ID and Tweet, and process through the python and send back the result from python to extension. Is it posible? What library need to use? It will something like pass messages between the extension and python program.

A: You can try using a python interpreter implemented in javascript, like Brython for example.
Another option is to create a python web server that listens for requests with twitter ids and responds with the processed information. Your extension will then communicate with the python server same as any other api server.


text:
Q: What should we have to pass to method to complete it What should I need to pass to complete this method. The error is :

The method fireSelect(String, String[], String[]) in the type DBConnection is not applicable for the arguments (String).

This is the method :
public static ResultSet fireSelect(String query, String[] types,
        String[] values) {
    try {
        PreparedStatement ps = getInstance().prepareStatement(query);
        if (types != null) {
            for (int i = 0; i < types.length; i++) {
                if (types[i].equals("int"))
                    ps.setInt((i + 1), Integer.parseInt(values[i]));
                else if (types[i].equals("string"))
                    ps.setString((i + 1), values[i]);
                else if (types[i].equals("double"))
                    ps.setDouble((i + 1), Double.parseDouble(values[i]));
            }
        }
        return ps.executeQuery();
    } catch (Exception e) {
        try {
            connection = null;
            if (cnt < 2) {
                connection = getInstance();
                cnt++;
                fireSelect(query, types, values);
            } else {
                cnt = 0;
            }
        } catch (Exception ee) {
            System.out.println("Exception :" + ee);
        }
    }
    return null;
}

and this is I have use to pass during cal this method
ResultSet rs = DBConnection.fireSelect(
                                    "select dealer_id,car_servicing,car_servicing,cost,features "
                                            + " from dealer_car,carservicing where "
                                            + "dealer_car.car_servicing=carservicing.car_servicing and dealer_id="
                                            + dealerId);

A: As your SQL doesn't expect any paramaters, you can simply do
ResultSet rs = DBConnection.fireSelect(sql, null, null);

A: It expects 3 arguments, and you provided only one.
Just call like,
ResultSet rs = DBConnection.fireSelect("Select Query", null, null);

A: you need to pass all 3 argumens to the function fireSelect()

A: Your SQL does'nt expect a paramter, it is build up by concatenation, what is not good. fireSelect seems to be e helper to use a prepared statement and you are avoiding this.
fireSelect("select * from ... where id=?", new String[]{"int"}, new String[]{"42"});

even this
fireSelect((String)null,(String[])null,(String[])null);

A: You're missing String[] types and String[] values, you could pass it as null (in your case), should be better if you call it like follow:
String sql = "select dealer_id,car_servicing,car_servicing,cost,features from
dealer_car,carservicing where dealer_car.car_servicing=carservicing.car_servicing
and dealer_id=:dealer_id";
String[] types = new String[]{"int"}; //or maybe string?
String[] vals = new String[]{dealerId};
ResultSet rs = DBConnection.fireSelect(sql, types, vals);

A: Your fireSelect method is expecting 3 arguments:
You can use something like:
ResultSet rs = DBConnection.fireSelect(
                  "select dealer_id,car_servicing,car_servicing,cost,features "
                    + " from dealer_car,carservicing where "
                    + " dealer_car.car_servicing=carservicing.car_servicing and dealer_id="
                    + dealerId,
                    new String[]{"int"},
                    new String[]{dealerId});


text:
Q: Status on the Tagged PDF project Does aynone know what the status of the Tagged PDF project is? How far has the LaTeX3 Team progressed on the time line from section 3 of "LaTeX Tagged PDF -- Feasibility Evaluation"?
Also, are there any new articles regarding the project?


text:
Q: How to show: there exists a 'choice function' $g:B\rightarrow A$ such that $f\circ g \circ f=f$ For the following question:

Prove that for every function $f:A\rightarrow B$ with $A$ non-empty, there exists a 'choice function' $g:B\rightarrow A$ such that $f\circ g \circ f=f$

I know that the function $g$ has to be $g(b)=a$ for $b\in B$, and $a\in f^{-1}(B)=A$.  My question is, do I have to worry about the case for $b'\in B\setminus f(A)$, since $f$ is not assumed to be surjective in the outset. If, I do, how do i account for it when constructing the function $g$.
Lastly, why is $g$ call a "choice" function?
Thank you in advance.

A: For each $b \in f(A)$, choose $a_b \in A$ such that $f(a_b)=b$.
Since $A$ is non-empty, let $a \in A$. Define $g \colon B \to A$ as
$$
g(b) = \begin{cases}
a_b & \textrm{if } b \in f(A), \\
a & \textrm{if } b \in B \setminus f(A).
\end{cases}
$$
Note that for each $x \in A$ we have $g(f(x)) = a_{f(x)}$, so that
$$
f(g(f(x))) = f(a_{f(x)}) = f(x).
$$
Therefore $f \circ g \circ f = f$.


text:
Q: How do I avoid persisting data through ViewState for a child control in ASP.NET? I have a control (say, a DataGrid or a ComboBox) which is a child of a user control.  I want to DataBind it on every request, rather than have it's state persist through ViewState.  I need to leave EnableViewState=true however.  This means, I think, that I need to call DataBind before TrackViewState() is called.
I read the fantastic blog post TRULY Understanding ViewState and it answers my question in 4. Initializing child controls programmatically.  However, the article's solutions are less-than-ideal: create child controls dynamically (I'm not and can't -- too much existing code), use a 3rd party CodeExpressionBuilder (would much prefer this was in code-behind), and use OnPreInit (which "doesn't help you what-so-ever if you are developing a CONTROL").
Since that article is rather old (circa 2006) I was hoping that newer versions of ASP.NET rectify the situation such that there are better solutions now.  So, community, are there any GOOD ways to do this?

A: Scott,
I think there's a misunderstanding of how ASP.NET Web Forms framework works. So just a little theory first.
ASP.NET Web Forms pages have design and code-behind files. Design file has HTML markup and "controls" which are reference tags to either user or custom controls. Every element that has attribute runat = "server" is server control (meaning it is accessible from the code behind by its ID).
When page is opened in the browser, ASP.NET takes design file and processes these control references and finally generates pure HTML.
ViewState is a hidden variable in HTML that keeps internal state of all controls that are marked with runat = "server" and also have property EnableViewState set to True.
Say you have DataGrid with EnableViewState = False. This grid has rows that contain server controls and you want them to be in ViewState. You still can have them have EnableViewState = True and be in ViewState and you still can bind to events for these sub-controls.
So even though DataGrid is not in ViewState, its children can be in ViewState and you can handle appropriate events.
You will need to initialize DataGrid in the PageLoad event every time if you want it to show data after every postback.
ViewState keeps internal state of control, so you can't have some properties of control in ViewState and others not in ViewState. But you can have child controls (they're not properties, they're subentities!) to be in ViewState even though parent control is not in ViewState.
Let me know if you want me to be more specific on this. If you want to go deep inside there's a brilliant book from Nikhil Kothari about developing controls. I think I saw it somewhere as e-book.


text:
Q: Series of timecodes to difference between each timecode and the first timecode How can I get the ms from the first timecode until each subsequent timecode in a series?
import pandas as pd

s = {1: pd.Timestamp('1970-01-28 05:28:52.235000'),
     2: pd.Timestamp('1971-02-02 12:13:23.230000'),
     3: pd.Timestamp('1970-09-04 17:14:53.120000')}

f = pd.DataFrame().from_dict(s, orient='index')

I have absolutely no idea how to do this and have tried googling without much luck.

A: Subtracting two TimeStamps gives you a Timedelta which you can convert to a float with .dt.total_seconds(). Use .iloc[0] to subtract the first element from the entire Series.
(f[0]-f[0].iloc[0]).dt.total_seconds()*1000
                                      # because milliseconds

#1    0.000000e+00
#2    3.199227e+10
#3    1.896396e+10
#Name: 0, dtype: float64

A: Go after this using DataFrame operations so that Pandas does the work. total_delta_time_ms shows the millisecond difference between the first value and each subsequent value.  row_delta_time_ms shows the milliseconds between each row.
import pandas as pd
from pandas import Timestamp
import numpy as np
import time

s = {1: Timestamp('1970-01-28 05:28:52.235000'),
 2: Timestamp('1971-02-02 12:13:23.230000'),
 3: Timestamp('1970-09-04 17:14:53.120000')}

f = pd.DataFrame().from_dict(s, columns=["start_time"], orient='index')
f["first_time"] = f["start_time"].values[0]
f["end_time"] = f["start_time"].shift(1)

f["total_delta_time"] = f["start_time"] - f["first_time"]
f["total_delta_time_ms"] = f["total_delta_time"].astype(np.int64) // 10**9

f["row_delta_time"] = f["start_time"] - f["end_time"]
f["row_delta_time_ms"] = f["row_delta_time"].astype(np.int64) // 10**9

print(f[["total_delta_time", "total_delta_time_ms"]])


text:
Q: Deselecting a ttk::checkbutton I have defined multiple ttk::checkbutton in a table. There requires a single Master checkbutton which will select or deselect all other checkbuttons at once. We can also select single checkbutton.
Now the problem is, I can select the child checkbuttons But I can not deselect them through code. I know I can deselect them all with a variable but I dont want to do that.Because all checkbuttons will then be linked. what to do.
Is Linking all checkbuttons with with different variables and then reseting them is the only option ?
Select code which works fine:
$childCheck state selected

the deselect code I have tried but failed:
$childCheck state deselected

A: Just got the answer. :)
Instead of deselected use !selected in state.
$childCheck state !selected


text:
Q: Magento installation error on server Currently I have downloaded magento on my system. After that I just uploaded that file to my server(in zip format). After upload I went to the server and extracted all the files from folder. Now as I want to install magento I browsed through my site url demo.sitename/magento/index.php it made one redirection for installation demo.siteurl/magento/index.php/install/ with one error like
404 - File or directory not found.
The resource you are looking for might have been removed, had its name changed, or is temporarily unavailable.

This came for there is no folder called install but one file is available and that is called as install.php.
Now I again browsed the page as demo.siteurl/magento/index.php/install. This time it showed me the  Magento's Installation Wizard! Now after clicking on  checkbox I agree to the above terms and conditions. and click on submit it again redirected me to the page http://demo.sitename/magento/Index.php/install/wizard/beginPost/ . After this it is again showing
`
404 - File or directory not found.
The resource you are looking for might have been removed, had its name changed, or is temporarily unavailable.

I have gone through many forums and blogs but did not found any solution. Below this I am attaching my.htaccess` file details
############################################
## uncomment these lines for CGI mode
## make sure to specify the correct cgi php binary file name
## it might be /cgi-bin/php-cgi

#    Action php5-cgi /cgi-bin/php5-cgi
#    AddHandler php5-cgi .php

############################################
## GoDaddy specific options

#   Options -MultiViews

## you might also need to add this line to php.ini
##     cgi.fix_pathinfo = 1
## if it still doesn't work, rename php.ini to php5.ini

############################################
## this line is specific for 1and1 hosting

    #AddType x-mapp-php5 .php
    #AddHandler x-mapp-php5 .php

############################################
## default index file

    DirectoryIndex index.php

<IfModule mod_php5.c>

############################################
## adjust memory limit

#    php_value memory_limit 64M
    php_value memory_limit 256M
    php_value max_execution_time 18000

############################################
## disable magic quotes for php request vars

    php_flag magic_quotes_gpc off

############################################
## disable automatic session start
## before autoload was initialized

    php_flag session.auto_start off

############################################
## enable resulting html compression

    #php_flag zlib.output_compression on

###########################################
# disable user agent verification to not break multiple image upload

    php_flag suhosin.session.cryptua off

###########################################
# turn off compatibility with PHP4 when dealing with objects

    php_flag zend.ze1_compatibility_mode Off

</IfModule>

<IfModule mod_security.c>
###########################################
# disable POST processing to not break multiple image upload

    SecFilterEngine Off
    SecFilterScanPOST Off
</IfModule>

<IfModule mod_deflate.c>

############################################
## enable apache served files compression
## http://developer.yahoo.com/performance/rules.html#gzip

    # Insert filter on all content
    ###SetOutputFilter DEFLATE
    # Insert filter on selected content types only
    #AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript

    # Netscape 4.x has some problems...
    #BrowserMatch ^Mozilla/4 gzip-only-text/html

    # Netscape 4.06-4.08 have some more problems
    #BrowserMatch ^Mozilla/4\.0[678] no-gzip

    # MSIE masquerades as Netscape, but it is fine
    #BrowserMatch \bMSIE !no-gzip !gzip-only-text/html

    # Don't compress images
    #SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png)$ no-gzip dont-vary

    # Make sure proxies don't deliver the wrong content
    #Header append Vary User-Agent env=!dont-vary

</IfModule>

<IfModule mod_ssl.c>

############################################
## make HTTPS env vars available for CGI mode

    SSLOptions StdEnvVars

</IfModule>

<IfModule mod_rewrite.c>

############################################
## enable rewrites

    Options +FollowSymLinks
    RewriteEngine on

############################################
## you can put here your magento root folder
## path relative to web root

    #RewriteBase /magento/

############################################
## uncomment next line to enable light API calls processing

#    RewriteRule ^api/([a-z][0-9a-z_]+)/?$ api.php?type=$1 [QSA,L]

############################################
## rewrite API2 calls to api.php (by now it is REST only)

    RewriteRule ^api/rest api.php?type=rest [QSA,L]

############################################
## workaround for HTTP authorization
## in CGI environment

    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

############################################
## TRACE and TRACK HTTP methods disabled to prevent XSS attacks

    RewriteCond %{REQUEST_METHOD} ^TRAC[EK]
    RewriteRule .* - [L,R=405]

############################################
## redirect for mobile user agents

    #RewriteCond %{REQUEST_URI} !^/mobiledirectoryhere/.*$
    #RewriteCond %{HTTP_USER_AGENT} "android|blackberry|ipad|iphone|ipod|iemobile|opera mobile|palmos|webos|googlebot-mobile" [NC]
    #RewriteRule ^(.*)$ /mobiledirectoryhere/ [L,R=302]

############################################
## always send 404 on missing files in these folders

    RewriteCond %{REQUEST_URI} !^/(media|skin|js)/

############################################
## never rewrite for existing files, directories and links

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-l

############################################
## rewrite everything else to index.php

    RewriteRule .* index.php [L]

</IfModule>

############################################
## Prevent character encoding issues from server overrides
## If you still have problems, use the second line instead

    AddDefaultCharset Off
    #AddDefaultCharset UTF-8

<IfModule mod_expires.c>

############################################
## Add default Expires header
## http://developer.yahoo.com/performance/rules.html#expires

    ExpiresDefault "access plus 1 year"

</IfModule>

############################################
## By default allow all access

    Order allow,deny
    Allow from all

###########################################
## Deny access to release notes to prevent disclosure of the installed Magento version

    <Files RELEASE_NOTES.txt>
        order allow,deny
        deny from all
    </Files>

############################################
## If running in cluster environment, uncomment this
## http://developer.yahoo.com/performance/rules.html#etags

    #FileETag none

Someone kindly tell me why this is error is happening? Any help and suggestions wil be really apprecaible. Thanks..
Edit
here is the server info
Cache-Control  no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Content-Encoding    gzip
Content-Length  6789
Content-Type    text/html; charset=UTF-8
Date    Sat, 24 Aug 2013 12:15:29 GMT
Expires Thu, 19 Nov 1981 08:52:00 GMT
Pragma  no-cache
Server  Microsoft-IIS/7.5
Set-Cookie  PHPSESSID=sotdvdsaqva9345igtt37sqvr2a5; expires=Sat, 24-Aug-2013 13:15:30 GMT; path=/magento; domain=demo.linkurl.info; httponly
Vary    Accept-Encoding
X-Powered-By    ASP.NET
X-Powered-By-Plesk  PleskWin

A: You are running the Microsoft IIS webserver, as IIS doesn't work with the .htaccess you need to active the url redirect to get it working, to do this open (or create) the web.config file in you webdirectory and insert this:
<rewrite>
<rules>
<rule name="Imported Rule 1" stopProcessing="true">
<match url=".*" ignoreCase="false" />
<conditions>
<add input="{URL}" pattern="^/(media|skin|js)/" ignoreCase="false" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsFile" ignoreCase="false" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" ignoreCase="false" negate="true" />
</conditions>
<action type="Rewrite\" url="index.php" />
</rule>
</rules>
</rewrite>

I never tried using Magento with the IIS webserver, so maybe it is a better solution to use the Apache server on your windows machine, this way you can use the .htaccess files that comes with Magento.

A: as per my comments on OP question, regarding magento server requirements, IIS is not supported. As suggested, install apache.


text:
Q: AngularJS and JayData Data Rendering issue i am creating app that uses jaydata angularjs j query mobile and webSql as database i created context using jaydata and store all data in webSql now i get using angularjs and append it into j query mobile html pages. i am thinking that angularjs is abilty of 2-way binding but when i add data and log it it stored in db but not shown on page until i refresh the whole page
here is my running application
some images of my flow are following
Main Screen of application

Click on Food Log
following screen comes
it is empty first time because not data logged yet

then click on plus button in upper right corner to add new log

Now fill this with data like below

and then click on Add food log and following screen comes

But actual it have to look like this one but for this I need to require refresh the page manually

as we know angularJs provide 2 way binding so do not need to refresh
help me in this issue this is a single page structure of J Query Mobile
Update Code
// JavaScript File For Controlling Food Module
var myApp = angular.module('myApp',[]);
myApp.controller('foodSelection',function($scope,$location)
{
var isSubmit = "false"; // Check Before Logging. Is All Field Fill oOr Not?
_context.onReady(
{
    success: function()
    {
        try
        {
            _context.FoodGroup.toArray().then(function (foodCatagories)
            {
                $scope.$apply(function ()
                {
                    try
                    {
                        $scope.foodCatagories = foodCatagories; // Attach Food Groups From DB To HTML Component
                    }
                    catch(error)
                    {
                        console.log("Inner Try  "+error);
                    }
                });
            });
        }
        catch(error)
        {
            console.log("Outer Try  "+error);
        }
    },
    error: function (error)
    {
        console.log("Error In Getting Data "+error);
    }
}); // End Of Context Redy Check
$scope.changeFoodCatagory = function(foodGroupObject)
{
    _context.FoodItem.filter("it.FoodGroup.FoodGroupID.startsWith('"+foodGroupObject.FoodGroupID+"')").toArray().then(function (foods)
    {
        $scope.$apply(function ()
        {
            try
            {
                $scope.foods = foods; // Attach FoodItem
            }
            catch(error)
            {
                console.log("Inner Try  "+error);
            }
        })
    });
}
$scope.changeFood = function(foodItemObject)
{
    _context.FoodItemWeight.filter("it.FoodItem.FoodItemID.startsWith('"+foodItemObject.FoodItemID+"')").toArray().then(function (serveSizes)
    {
        $scope.$apply(function ()
        {
            try
            {
                $scope.serveSizes = serveSizes; // Attach ServeSize Of The Selected Food
            }
            catch(error)
            {
                console.log("Inner Try  "+error);
            }
        })
    });
}

$scope.changeServeSize = function(foodWeightObject)
{
    var noOfServes = {};
    noOfServes.cast = [{value: "1",text: "1"},{value: "2",text: "2"},{value: "3",text: "3"},{value: "4",text: "4"},{value: "5",text: "5"},{value: "6",text: "6"},{value: "7",text: "7"},{value: "8",text: "8"},{value: "9",text: "9"},{value: "10",text: "10"},{value: "11",text: "11"},{value: "12",text: "12"},{value: "13",text: "13"},{value: "14",text: "14"},{value: "15",text: "15"},{value: "16",text: "16"},{value: "17",text: "17"},{value: "18",text: "18"},{value: "19",text: "19"},{value: "20",text: "20"}];
    $scope.noOfServes = noOfServes; // Attach No Of Servings
}
$scope.changeServeNo = function()
{
    isSubmit = "true";  // Mark True As All Fields Are Select
}
$scope.go = function()
{
    if(isSubmit == "true")
    {
        var date = Date.now();
        var calcories = (($scope.food.Energ_Kcal/100)*$scope.serveSize.Gm_Wgt)*$scope.serveNo.value;
        var quant = $scope.serveNo.value;
        _context.FoodItem.filter("it.FoodItemID.startsWith('"+$scope.food.FoodItemID+"')").forEach(function (foods)
        {
            $scope.$apply(function ()
            {
                try
                {
                    _context.User.filter("it.UserID.startsWith('"+1+"')").forEach(function(user)
                    {
                        _context.FoodLog.add({Quantity:quant,TotalCalories:calcories,DateTime:date,FoodItem:foods,User:user});
                        _context.saveChanges();
                    });
                }
                catch(error)
                {
                    console.log("Inner Try  "+error);
                }
            })
        });
        //$.mobile.changePage( "index.html#foodscreen")
        $location.hash('foodscreen');
    }
    else
    {
        alert("Select All Fields");
        return false;
    }
} // End Of Go Function
}); // End Of Controller
myApp.controller('foodLogCtrl',function($scope,$route)
{
_context.onReady(
{
    success: function()
    {
        try
        {
            _context.FoodLog.include("FoodItem").include("FoodItem.FoodGroup").toArray().then(function(foodLogs)
            {
                $scope.$apply(function ()
                {
                    try
                    {
                        /*var totalCaloriesGained = 0;
                        for(var i=0; i<foodLogs.length; i++)
                        {
                            totalCaloriesGained += parseFloat(foodLogs[i].TotalCalories);
                        }
                        alert(totalCaloriesGained);*/
                        $scope.foodLogs = foodLogs; // Attach Food Logs From DB To HTML Component
                    }
                    catch(error)
                    {
                        console.log("Inner Try  "+error);
                    }
                });
            });

        }
        catch(error)
        {
            console.log("Outer Try  "+error);
        }
    },
    error: function (error)
    {
        console.log("Error In Getting Data "+error);
    }
}); // End Of Context Redy Check
$scope.deleteLog = function(id)
{
    try
    {
        _context.FoodLog.filter('it.FoodLogID == '+id+'').forEach(function(foodlog)
        {
            _context.FoodLog.remove(foodlog);
            _context.saveChanges();
            //$route.reload();
        });
    }
    catch(error)
    {
        console.log("Error Catch During Deletion "+error);
    }
    /*$.mobile.changePage( $("#foodscreen"),{
            allowSamePageTransition: true,
            transition: 'none',
            reloadPage: true
        });*/
    $('#foodLoggedID_'+id).hide();
}//End Of Delete Function
});
myApp.controller('foodDetailLogCtrl',function($scope)
{
$scope.editLog = function(id)
{
    //alert(id);
    //var obj = [{foodName:"Hello"}];
    try
    {
        _context.FoodLog.filter('it.FoodLogID == '+id+'').include("FoodItem").include("FoodItem.FoodGroup").toArray().then(function(foodDetails)
        {

            $scope.$apply(function ()
            {
                $scope.foodDetails = foodDetails;
            });
        });
    }
    catch(error)
    {
        console.log("Error Catch During Deletion "+error);
    }
}
});

and i write html like this

                {{foodLog.FoodItem.Shrt_Desc}}
                {{foodLog.FoodItem.FoodGroup.Description}}
                {{foodLog.TotalCalories}}

                Delete

A: it happens because saveChanges() is async
and your $apply runs before saveChanges() finished
we've released an angularjs module, please use that module so you do not have to manually call $apply, your code will be much shorter and easier to understand
you can find more info about it in our blog


text:
Q: Declaring INT variable to return in MYSQL Function problem I'm trying to build a mysql function which inserts values into a table and returns me the last_id inserted, which should be the same after executing the insertion. But Xampp gives me an error in the line where im declaring the "last_bill_id" variable. Can someone please help me to understand what am I doing wrong?
Here is the code for the function:
CREATE FUNCTION insert_bill(

        client_id varchar (12),
        bill_date date
    ) RETURNS INT
    BEGIN
        DECLARE last_bill INT;
        INSERT INTO bill
        (
            client_id, bill_date
        )
         VALUES
        (
            client_id, bill_date
        );
        SET last_bill = LAST_INSERT_ID();
        RETURN last_bill;
    END $$
    DELIMITER ;

Error: #1064 - Something is wrong about 'INT

A: you need another DELIMITER at the start
DELiMiTER $$
CREATE FUNCTION insert_bill(

    client_id varchar (12),
    bill_date date
) RETURNS INT
DETERMINISTiC
BEGIN
    DECLARE last_bill INT;
    INSERT INTO bill
    (
        client_id, bill_date
    )
     VALUES
    (
        client_id, bill_date
    );
    SET last_bill := LAST_INSERT_ID();
    RETURN last_bill;
END $$
DELIMITER ;


text:
Q: Delete rows from binding source with foreign key I have a DataSource with 2 tables one projectDiamter and other diameterSet. ProjectDiameter id contains primary key and diameterset has foreign key constraint with same key.
Now when I select row from projectdiameter table diameterset DataGridView get filtered accordingly. I have lots of rows in diameterset (lets say 15000 for selected project only) which I want to delete when delete button is pressed.
I wanted to know which is the fastest way to delete it from DataGridView and SQL table.
I tried following code but wanted to check if there is any better way of getting the same.
FKProjectDiameterBindingSource.MoveFirst()
For j As Int16 = 0 To FKProjectDiameterBindingSource.Count - 1
    For i As Int16 = 0 To FKDiameterDiameterSetBindingSource.Count - 1
        FKDiameterDiameterSetBindingSource.Clear()
        FKDiameterDiameterSetBindingSource.MoveFirst()
        FKDiameterDiameterSetBindingSource.RemoveCurrent()
    Next
    FKProjectDiameterBindingSource.MoveNext()
Next

Me.Validate()
DiameterTableAdapter.Update(RSM3DDB1.Diameter)
DiameterSetTableAdapter.Update(RSM3DDB1.DiameterSet)

A: Does the foreign key relationship exist formally in the database? That is, is there an actual relationship defined in SQL? If so, I'd suggest setting that relationship to CASCADE DELETE and then all you have to do is call DiameterSetTableAdapter.UPDATE after you update Diameter.
A good explanation on CASCADE DELETE is here
https://www.mssqltips.com/sqlservertip/2365/sql-server-foreign-key-update-and-delete-rules/ Note that the keyword is just "Cascade" but you apply it to DELETE, the article explains ("It is not necessary that the same rule be applied for both update and delete operations. There may be different rules for each of the update and delete operations on a single FK constraint.")
If the relationship isn't formal, that is it logically exists but isn't enforced, then I'd put a trigger on the Diameter table and in that trigger delete all the rows in DiameterSet where the DiameterID equals the  deleted DiameterID. Note that in a trigger a row that is modified (as opposed to deleted) will be in both the INSERTED and DELETED temporary tables, so you have to take steps to make sure you're not removing rows that reference a modified Diameter.
If you take this second approach, you can still just run the 2 UPDATE procedures on the 2 table adapters in VB, it's just more coding in SQL than setting the CASCADE DELETE.
Both approaches are MUCH more efficient than doing it in VB, and it can add up if you have hundreds of rows affected.
Using either of these also has the advantage of being atomic, whereas your approach is not.


text:
Q: How to set Base URI to Spring WebClient I am trying to create a Spring WebClient to call REST API. For that, I wrote the following piece of code.
@Bean
public WebClient defaultWebClient() {

    var tcpClient = TcpClient.create()
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3_000)
            .doOnConnected(connection ->
                    connection.addHandlerLast(new ReadTimeoutHandler(3))
                            .addHandlerLast(new WriteTimeoutHandler(3)));

    return WebClient.builder()
            .baseUrl("https://test.com")
            .clientConnector(new ReactorClientHttpConnector(HttpClient.from(tcpClient)))
            .defaultHeader(HttpHeaders.ACCEPT, "application/vnd.api+json")
            .build();
}

then the actual URI with the following code.
String user = webClient
                .get()
                .uri(URI.create("/api/v1/user/1"))
                .header("Authorization", TOKEN)
                .header(HttpHeaders.ACCEPT, "application/json")
                .retrieve()
                .bodyToMono(String.class)
                .block();

but when the above code executed then it throws the following exception.

{"timestamp":"1608209276546","level":"ERROR","thread":"http-nio-8080-exec-1","mdc":{"tenantId":null},"logger":"org.apache.catalina.core.ContainerBase.[Tomcat].[localhost].[/].[dispatcherServlet]","message":"Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.web.reactive.function.client.WebClientRequestException: Connection refused: no further information: /127.0.0.1:12012; nested exception is io.netty.channel.AbstractChannel$AnnotatedConnectException: Connection refused: no further information: /127.0.0.1:12012] with root cause","context":"default","exception":"java.net.ConnectException: Connection refused: no further information\r\n\tat java.base/sun.nio.ch.SocketChannelImpl.checkConnect(Native Method)\r\n\tat

I am not sure where I need to change here so that it starts pointing to base URI instead of localhost (127.0.0.1:12012).
Another thing is if I pass the fully qualified name (https://test.com/api/v1/user/1) on API call then it works fine.

A: From javadoc, method uri(URI uri)

Specify the URI using an absolute, fully constructed URI

so this version of method does not use base url from configuration.
Instead, you should have specified URI using UriBuilder, which is injected into method uri(Function<UriBuilder,URI> uriFunction).
String user = webClient
            .get()
            .uri(uriBuilder -> uriBuilder.path("/api/v1/user/1").build())
            ...

A: There are two methods in WebClient.UriSpec that could help.
interface UriSpec<S extends RequestHeadersSpec<?>> {

    S uri(String uri, Object... uriVariables);

    S uri(String uri, Map<String, ?> uriVariables);

    ...
}

In the simplest case just pass String instead of URI as the argument.
String user = webClient
                .get()
                .uri("/api/v1/user/1")        // <- just String
                .retrieve()
                .bodyToMono(String.class)
                .block();

A: You're using TcpClient, in my version I used HttpClient and had to specify the baseUrl parameter on that as well.
i.e.
HttpClient httpClient = HttpClient
                        .create()
                        .baseUrl(getRootUrl())
                        .responseTimeout(Duration.ofMillis(<timeout in millis>));

return WebClient
                        .builder()
                        .baseUrl(getRootUrl())
                        .clientConnector(new ReactorClientHttpConnector(httpClient))
                        .defaultHeaders(headers -> {
                            if (!headers.containsKey(HttpHeaders.CONTENT_TYPE)) {
                                headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM.toString());
                            }

                            headers.add("Authorization", "Bearer " + accessKey);
                        })
                        .build();

Hope that helps.


text:
Q: FlatList and Scrollview disappear items while pull to refresh while pull to refresh the flatlist or even a scrollview i get some data from the api and if the data i get is less then the data i already displayed the whole items disappear and if it's higher it's only display the new one and if it's equal everything seems okay also if i go to other page then i return everything seems good
note : i display list of images i fetch from the api using card item from native base
 _getFilesOnRefresh = () => {
  axios.get(GET_ALL_FILES_URL+this.state.company_id, {
      headers: {
          'api_token':this.state.api_token
      }
  })
      .then(resp =>{
          this.state.files =  resp.data[0];
          //set the cache to the new data
          this._setCache(resp.data[0]);
          this._AppendUploadingFiles();
          if(this.state.files.data.length == 0)
          {

              this.setLoading(true);
              let message = "You Don\'t Have Any Files";
              alert_message(message);
              this._middlePageMessage(message);
          }
          else
          {

              this.setLoading(false);
              // this.state.files.data = this.state.files.data.reverse();
              success_message("Displayed "+this.state.files.data.length+" Files");
          }
          // stop refreshing
          this.setRefresh(false);
      })
      .catch(function(error){
          console.log('on refresh error',error);
          // console.log(error)
          let message = 'Check Your Connection!';
          // this.setLoading(true);
          alert_message(message);
          // this._middlePageMessage(message);
          // stop refreshing
          this.setRefresh(false);
      }.bind(this)); };
_handleRefresh = () => {
    if(!_getUploadingFlag()){// if he's uploading don't do anything else refresh
        this.setRefresh(true);
        this._getFilesOnRefresh();
    }
};

render() {
if(this.state.isLoading){
  return(
      <Container style={styles.container}>
        <MenuHeader title="My Requests" obj={this.props}/>
          {this.state.LoadingOutput}
            <FabAddFiles currentPage={this}/>
      </Container>
  );
}
else{

  for (let index = 0; index < this.state.files.data.length; index++) {
    if(this.state.files.data[index].file_status == 'pending' || this.state.files.data[index].file_status == 'in-progress')
      this.state.files.data[index].type = fileStatus['pending'];
    else if(this.state.files.data[index].type == 'Sales'){
      this.state.files.data[index].type = <Icon ACTIVE name="document" style={{color:colors.success_color,fontSize:45}}/>;
    }else if(this.state.files.data[index].type == 'Purchase'){
      this.state.files.data[index].type = <Icon type="FontAwesome" name="shopping-cart" style={{color:colors.danger_color,fontSize:40}}/>;
    }
    if(this.state.files.data[index].images.length == 0){
      //create image path if it's not exist
      let imagePath = {image_path:'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRvcJY57vM025nSOBjfKbo6pC0pMIMMHEdDcJZprWFigxXCIqhRVA'};
      this.state.files.data[index].images.push(imagePath);
    }
  }
  // create list
  let files_elemnts = this.state.files.data.map(item => {
      return(
          <TouchableHighlight onPress={() => this.props.navigation.navigate('ShowFile' , {item:item})}>
              <Content  style={styles.File_box} >
                  <Card style={styles.card} >
                      <CardItem style={styles.card_item}>
                          <Left style={{flex:1,borderRadius:15}}>
                              <Image
                                  // resizeMethod={'resize'}
                                  source={{uri: item.images[0].image_path}}
                                  indicator={ProgressPie}
                                  // renderError={console.log('error')}
                                  indicatorProps={{
                                      size: 80,
                                      color: colors.secondary_color,
                                      unfilledColor: colors.third_color
                                  }}
                                  style={{
                                      width: 100,
                                      height: 120,
                                  }}
                                  borderRadius={10}
                              />
                          </Left>

                          <Body style={{flex:1.4}}>
                          <Text style={styles.file_status}>{item.description.length > 0 ? item.description : headerStatus[item.file_status]}</Text>
                          <Text note style={styles.date}>
                              <Icon active name="calendar" style={styles.icon}/> {item.date}
                          </Text>
                          <Text note style={styles.time}><Icon active name="time" style={styles.icon}/> {item.time}</Text>
                          {item.amount !=0 ? <Text style={styles.money}>AED {item.amount}</Text> :null}
                          </Body>

                          <Right style={{flex:0.4}}>
                              {item.type}
                              <Text style={styles.mainIcon}></Text>
                              {item.file_status == 'in-progress' || item.file_status == 'pending'  ? null :fileStatus[item.file_status] }
                          </Right>

                      </CardItem>
                  </Card>
              </Content>
          </TouchableHighlight>
      )
  });

return (
      <Container style={styles.container}>
      <MenuHeader title="My Requests" obj={this.props}/>
      {/*<View style={{flex:0.1}}>*/}
      {/*/!*<Text style={styles.headeing}>{this.state.company_name}</Text>*!/*/}
      {/*</View>*/}
          <ScrollView refreshControl={
              <RefreshControl
                  refreshing={this.state.refresh}
                  onRefresh={this._handleRefresh}
              />
          }>
      <View style={{flex:1}}>
            {files_elemnts}
        </View>
      </ScrollView>
        <FabAddFiles currentPage={this}/>
      </Container>); }

in case i use flatlist
<FlatList
                    style={{marginBottom:20}}
                    onRefresh={this._handleRefresh}
                    refreshing={this.state.refresh}
                    initialNumToRender={30}
                    extraData={this.state.reRender}
                    data={this.state.files.data}
                    keyExtractor={item => item.id}
                    renderItem={({item}) =>
                        <TouchableHighlight onPress={() => this.props.navigation.navigate('ShowFile' , {item:item})}>
                            <Content  style={styles.File_box} >
                                <Card style={styles.card} >
                                    <CardItem style={styles.card_item}>
                                        <Left style={{flex:1,borderRadius:15}}>
                                            <Image
                                                // resizeMethod={'resize'}
                                                source={{uri: item.images[0].image_path}}
                                                indicator={ProgressPie}
                                                // renderError={console.log('error')}
                                                indicatorProps={{
                                                    size: 80,
                                                    color: colors.secondary_color,
                                                    unfilledColor: colors.third_color
                                                }}
                                                style={{
                                                    width: 100,
                                                    height: 120,
                                                }}
                                                borderRadius={10}
                                            />
                                        </Left>

                                        <Body style={{flex:1.4}}>
                                        <Text style={styles.file_status}>{item.description.length > 0 ? item.description : headerStatus[item.file_status]}</Text>
                                        <Text note style={styles.date}>
                                            <Icon active name="calendar" style={styles.icon}/> {item.date}
                                        </Text>
                                        <Text note style={styles.time}><Icon active name="time" style={styles.icon}/> {item.time}</Text>
                                        {item.amount !==0 ? <Text style={styles.money}>AED {item.amount}</Text> :null}
                                        </Body>

                                        <Right style={{flex:0.4}}>
                                            {item.type}
                                            <Text style={styles.mainIcon}></Text>
                                            {item.file_status == 'in-progress' || item.file_status == 'pending'  ? null :fileStatus[item.file_status] }
                                        </Right>

                                    </CardItem>
                                </Card>
                            </Content>
                        </TouchableHighlight>}
                />


text:
Q: Immutability-Helper Updating One Property but not Others? I have a jsx style that looks like this:
let styles = {
    appBarStyle: {
        display: 'flex',
        flexWrap: 'nowrap',
        WebkitFlexFlow: 'nowrap',
        flex: '1 1 0%',
        alignItems: 'center',
        justifyContent: 'space-between',
        padding: '0',
        margin: '0',
        listStyle: 'none',
        backgroundColor: '#00bcd4',
        fontFamily: 'Roboto',
        minHeight: '64px',
        color: 'white',
        fontSize: '2em',
        margin: '0px',
        padding: '0px',
        width: '100%',
        zIndex: '2',
        position: 'static',
        top: 'auto',
        left: 'auto',
        right: 'auto'
    }
};

I want it to be position:fixed on smartphones and IOS, but not on desktops.
So I have some code that uses immutability-helper:
if (useFixedMenuBar) {
    styles = update(styles, {
        appBarStyle:{top: {$set: '0px'}},
        appBarStyle:{left: {$set: '0px'}},
        appBarStyle:{right: {$set: '0px'}},
        appBarStyle:{position: {$set: 'fixed'}},
}

After the call to update, the position property is correctly updated to fixed, but the top, left, and right properties are not updated to 0px -- they still are set to auto.
What am I missing?

A: I think you're overwriting what's getting set to the appBarStyle key so only the last one is set, and then the update happens. Try:
styles = update(styles, {
    appBarStyle:{
        top: {$set: '0px'},
        left: {$set: '0px'},
        right: {$set: '0px'},
        position: {$set: 'fixed'},
    }
})


text:
Q: How to call function as auto increment in laravel I'm trying to call my function as auto increment value in laravel, but i dont know how to do it.
The function i'm trying to use is
public function generateRandomString()
    {
        $pass = substr(str_shuffle("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 6);
        return $pass;
    }

and the column im trying to call the function are 'No_Resi'
public function up()
    {

        Schema::create('order', function (Blueprint $table) {
            $table->increments('No_Resi');
            $table->string('Nama_Lengkap',100);
            $table->text('Alamat_Pengambilan',100);
            $table->text('Alamat_Tujuan',100);
            $table->integer('No_Telepon_Pengirim');
            $table->integer('No_Telepon_Penerima');
            $table->enum('Jenis Barang',['Makanan','Dokumen','Barang Pecah Belah','Pakaian',
                                        'Obat-Obatan','Buku','Lainnya']);
        });
    }

so the output should be something like this

No_Resi
Nama_lengkap

1B45CY
someone

9K0L7T
nobody


text:
Q: Find latest matching item in another table Consider the following two tables, named tbl_users and tbl_actions respectively:
user_id     user_name     capture_date
u123        John Smith       2016-04-01
u124        Hannah Montana   2015-10-07
u125        James Bond       2014-07-28

user_id     user_alias      use_date
u123         Jonathan Smith  2012-01-01
u125         Double-O Seven  2012-02-04
u125         O-O-Seven       2015-11-25

I want to join them such that I would find the "latest used" alias of each user that is before their capture date. So the expected output is:
user_id     user_name     capture_date   latest_alias_by_then
u123        John Smith       2016-04-01     Jonathan Smith
u124        Hannah Montana   2015-10-07
u125        James Bond       2014-07-28     Double-O Seven

How do you do that efficiently in SQL? I am using Microsoft SQL Server so functions like OVER and RANK are available too.

A: SELECT  *
FROM    (
        SELECT  u.*, a.user_alias,
                ROW_NUMBER() OVER (PARTITION BY u.user_id ORDER BY a.use_date DESC) rn
        FROM    tbl_users u
        LEFT JOIN
                tbl_actions a
        ON      a.user_id = u.user_id
                AND a.use_date <= u.capture_date
        ) q
WHERE   rn = 1

or
SELECT  *
FROM    tbl_users u
OUTER APPLY
        (
        SELECT  TOP 1
                user_alias
        FROM    tbl_actions a
        WHERE   a.user_id = u.user_id
                AND a.use_date <= u.capture_date
        ORDER BY
                use_date DESC
        ) q

Create an index on tbl_actions (user_id, use_date) for the queries to work faster.
Either of these methods can be more efficient than the other, depending on how many users and how many actions per user you have.


text:
Q: KendoUI combobox on focus $("#" + id).tie("focus", function () {
    alert();
});

I am trying to get a Kendo combobox to do something when given focus. I cannot seem to be able to get the focus event though, I replaced the actual contents with an alert to test, but cannot get the alert to be present. What do I need to tie the focus to?

A: Two questions to keep in mind:

*

*Kendo UI wraps your input element with some additional HTML that is used to maintain visual compatibility (among others) between browsers. So when you actually say $("#" + id) you are selecting a hidden input element.

*Kendo UI sometimes creates elements not when you think but a little later (example, when you get data from a server might happen that the HTML is not generated until you the data is received).

So, you should use:
$("#" + id).data("kendoComboBox").input.on("focus", function () {
    console.log("here");
});

Where I use $("#" + id).data("kendoComboBox").input for actually accessing the input element that is being used by the user. Documentation on input here
See it here: http://jsfiddle.net/OnaBai/qgrjsak4/3/


text:
Q: Calculating Previous Month So i have this function that basically takes an input of an integer and based off of today's date, it goes back to that 'n' number of months. So for example today's date is Nov 20, 2012. If 'n' = 1, then it returns Oct 20, 2012 and so on.
The problem that Im facing is that everythime months is between Feb-May, the years variable is subtracted by one. So for example, If n = 6, it should return May 20, 2012. Instead it returns May 20, 2011.
I thought it could be a leap year issue but when I tested it out with n = 18, it returned May 20, 2010 instead of May 20, 2011 and 2011 is not a leap year.
Does anyone know what I can do here to avoid this?
lastNmonths = function(n) {
   var date = new Date();

   if (n <= 0)
       console.log( [date.getFullYear(), date.getMonth() + 1 , date.getDate()].join('-'));

  var years = Math.round(n / 12);
  var months = n % 12;

   if (years > 0)
       date.setFullYear(date.getFullYear() - years);

   if (months > 0) {
       if (months >= date.getMonth()) {
           date.setFullYear(date.getFullYear() );
           months = 12 - months;
           date.setMonth(date.getMonth() + months );
       } else {
           date.setMonth(date.getMonth() - months);
       }
   }

   console.log( [date.getFullYear(), date.getMonth() + 1, date.getDate()].join('-'));
};

A: You approach is unnecessarily complicated and necessarily error-prone.  Use the built-in overflow control of Date instances instead:
var n = 6;
var d = new Date();
d.setMonth(d.getMonth() - n);


text:
Q: How do I disable express logs in my node.js CLI? I am new to node.js and I am trying to move away from using console.log for debugging everything. I am trying to use
debug("test message")

instead of console.log for everything.
I installed the debug npm package, and it instructed me to:
set DEBUG=* node server.js

But, with my express package, I get the following:

The app message in blue is the only relevant message to me since I am trying to use that instead of console.log. How can I get rid of these express logs? Do you think at some point they would be important?

A: you can use it like
dbg=debug('myserver:app')
and output messages with
dbg('A new message')
also to output only those messages that you want
set DEBUG=myserver:app node server.js
you can also exclude with - or include like myserver:app,express:*
with DEBUG environmental variable you can specify what to output or no. more information https://www.npmjs.com/package/debug check the wildcards and examples

A: The correct command which worked for me is:
set DEBUG=*,-express:*  node server.js

this will enable all messages, then exclude everything starting with express:


text:
Q: Idiom for explaining something too thoroughly Is there an idiom for explaining something in extreme detail? I know there is an idiom for getting rid of something "root and branch", but based on the examples I've seen, this cannot be used in this kind of context, or can it?
I am looking for a phrase of some sort, somewhat pejorative but a funny one – an idiom, colloquialism or something multi-word. In my language we have a saying that someone explains something and "includes the root" or "explains every pond and pool", e.g. when someone asks the shortest way from point A to point B, and instead of telling which one it is, you start describing every rock and tree and bush on the way, which really is not at all informative. Pretty much an exact opposite to "cutting to the chase".

A: Another possibility for a single-word expression of this is pedantic (describes the person or the explanation), perhaps preceded by unnecessarily or excessively or etc.
"Given the level of the class, the professor's lectures were often unnecessarily pedantic."
pedantry refers to the practice of being pedantic. "The class sessions were filled with pedantry." A pedant is someone who often speaks or writes this way.

A: Labor the point

Explain or discuss something at excessive or unnecessary length.

Also known as belaboring the point.

to explain or insist on excessively.
  to keep explaining or insisting on to excess

example usage:

Her habit of belaboring the obvious makes her a very boring speaker.

Note US/UK variation in spelling of labor/labour.

A: This is sometimes described as getting "bogged down" in the details.
"Bog" is a synonym for "swamp", suggesting that someone is getting stuck, as if they are wading in a swamp, instead of making progress.

A: Perhaps explicate would convey the meaning you want.
From Oxford Advanced Learner's Dictionary:

explicate something - (formal) to explain an idea or a work of
  literature in a lot of detail

A: The idiom that always comes to mind for me in this situation is the following:

"I asked you what time it is, but you told me how to build a clock."

A: In my shop we call this getting too deep into the weeds, which is the opposite of taking the thirty-thousand-foot view.
I'm afraid business-communications outfits like mine are sorta heirs to the Madison Avenue tradition that created gems like run it up the flagpole and see who salutes.

A: If someone is going into too much detail one phrase is

Can't see the wood for the trees.

Which means obscuring the big picture with irrelevant detail.
In this example "wood" means "forest" and not "plank", and without this explanation the example phrase would mean the opposite!

On a different tack, repeating too much detail can be said to be

Explaining ad nauseam.

Which is a Latin term (in modern use) for an argument or discussion that has continued 'to the point of nausea'.

A: "Over-egging the pudding"
Perhaps most relevant to being overly dramatic, but conveys the meaning of providing more substance than is actually required, for the context.
Or
"Laying it on a bit thick"
Or
"Teaching one's grandmother how to suck eggs"
Needlessly explaining to an audience something they are well aware of. Needless, because you ought to realize their awareness.
Or
"Preaching to the choir"
Trying to convince someone of something they are clearly already signed up to the concept of: The choir would be at the front of the church and keen enough on the whole business to occupy that privileged position.
(I'm British by the way, so maybe these are British idioms. I'll stop now in case I start explaining too thoroughly :-)

A: Overexplaining sounds like a good single-word option here. It is fairly intuitive in its meaning and is very likely to be understood by the other party even without prior knowledge of the word.
I could not find any definition or confirmation in a conventional dictionary, but an example from this online dictionary suggests your intended usage:

overexplain in British
[ˌəʊvərɪkˈspleɪn]
verb

to explain in too much detail

Wiktionary suggests a similar definition (please note that, being an open wiki, Wiktionary's information is not guaranteed to be 100% accurate, is not regarded an authoritative source and may contain accidental or deliberate errors):

Etymology
over- + explain
Verb
overexplain
(third-person singular simple present overexplains, present participle overexplaining, simple past and past participle overexplained)
(transitive) To explain at unnecessary length or in too much detail.

A: "Going twice around the barn to get to the house" is common in Ohio where I grew up.

A: I may add splitting hairs (definition), but that person might also be said to provide circumvoluted explanations (see circumvolute).

A: You can say one went around the world and back in their explanation.
You can also say they covered every nook, cranny, and then some
Or they simply went off.
Some of these need context though.

A: Some additional suggestions:
beating around the bush - when someone keeps talking and won't get to
   the point
beating it to death - when someone keeps talking and won't
   get off a topic
the nitty-gritty - exhaustive detail on a topic, not necessarily a
   negative connotation
all the gory details - same as above

A: "Every jot and tittle" and equivalently "Dotting the i's and crossing the t's" are idioms for extreme attention to detail. The former is accredited to Jesus himself (Matthew 5:18).
The question was about extremely detailed, not excessive explanations.

A: If someone is in the middle of an overly long explanation, you could interrupt and say "I don't need to know how the sausage is made." That might be closer to what you want.

A: An explanation that is much longer or more detailed than necessary can be called 'long-winded':
e.g. 'He launched into a long-winded explanation of the history of locomotive engines'

A: S/he blinded me with science ...
In response to Sven's comment:
https://www.youtube.com/watch?v=lnGVxfKXu94
I love Thomas Dolby's song, but it's not true to the meaning of the the phrase (and the phrase is not exactly what the original question was asking for).

A: "mansplaining" is a classic, though it only applies to half the population doing it, and is obviously pejorative.
See video of Silicon Valley scene featuring mansplaining.
If it's not pejorative, it could simply be called a thorough explanation. For an idiom, it could be "dotting the i's and crossing the t's."
If it's not necessarily performed by a man, but meant in a pejorative sense, it could be over-explaining, pedantic, or "whipping a dead horse."


text:
Q: How to remove multiple lines (block of code) in multiple files in JS? I am using Hashlips code for generating NFTs (10 000 NFTs), however, I have added data for Solana, which I've decided not go with and I would like to remove it. The code of block is in every single NFT, it would take a lot of time to delete manually.
The files are in json folder and the same code is:
"properties": {
    "files": [
      {
        "uri": "image.png",
        "type": "image/png"
      }
    ],
    "category": "image",
    "creators": [
      {
        "address": "xxxxxxxxxxxxxxxxxxxxxx",
        "share": 100
      }
    ]
  },

A: You can use Node.js to read files or directories of file (documentation of file system).
Then, using JSON.parse() you can create an object with filtered data.
Finally, you can rewrite on each files those new objects.
It can look like this:
import { readdir, readFile, writeFile } from 'fs/promises';

try {
  const files = await readdir('./jsons');
  for (const file of files) {
    const fileContent = await readfile(`./jsons/${file}`, {encoding: 'UTF-8'};
    const json = JSON.parse(fileContent);
    // Do magic
    writeFile(`./jsons/${file}`, json, {encoding: 'UTF-8'})
  }
} catch (err) {
  console.error(err);
}

Consider saving your files somewhere else before executing your script.


text:
Q: Legend in a bar plot in Matlab How can I plot a legend in a bar plot in Matlab? Here is the code:
Y = [1.5056
0.72983
3.4530
3.2900
1.4839
12.9 ];
n = length(Y);
h = bar(Y);
colormap(summer(n));
grid on

l = cell(1,6);
l{1}='L'; l{2}='B'; l{3}='R'; l{4}='P'; l{5}='h'; l{6}='Ri';
legend(h,l);

This give an error: Warning: Ignoring extra legend entries. I tried solutions which I found on the SO and web, but I couldn't resolve this.

A: Instead of legend, you can solve it using the tick labels for example:
set(gca,'xticklabel', l)

This will label each bar. If you want to use legend you need to have a matrix data, so the bar plot will show several bars per entry. For example
Y=rand(10,6)
h = bar(Y);
colormap(summer(n));
grid on
l = cell(1,6);
l{1}='L'; l{2}='B'; l{3}='R'; l{4}='P'; l{5}='h'; l{6}='Ri';
legend(h,l);

Or, you can use different bar() calls in this way:
h = bar(diag(Y));

But then you'll get a displacement per each bar:

So, the only way really to do that using legend is to plot each bar seperatly, similar to what is discussed here.

A: Further to bla's answer, you can use
h = bar(diag(Y),'stacked');

if you want to avoid the displacement.


text:
Q: Ant Build giving error when using the itext jars  [javac] symbol  : method setDocumentFromString(java.lang.String)
    [javac] location: class org.xhtmlrenderer.pdf.ITextRenderer
    [javac]         renderer.setDocumentFromString(html);
    [javac]                 ^
    [javac] Note: Some input files use or override a deprecated API.
    [javac] Note: Recompile with -Xlint:deprecation for details.
    [javac] Note: Some input files use unchecked or unsafe operations.
    [javac] Note: Recompile with -Xlint:unchecked for details.
    [javac] 1 error

Im getting this error .im using itext jars with ant build
de.huxhorn.lilith.3rdparty.flyingsaucer.core-renderer-8RC1.jar /
itext-2.0.8.jar
This works fine with PSVM ...And no complie errors shown in the ide..
but when i runnig the ANt build this error is appearing..
Why is this happening ??

A: The dependent jar may not be added correctly to your build classpath and your IDE has it in the build path.

A: It looks like the org.xhtmlrenderer.pdf.ITextRenderer class in the jar that is resolved by Ant build doesn't include the method 'setDocumentFromString'
Can you please take a look on your jar and ensure that the method is really there?


text:
Q: Is it possible for the light (photons) to turns into normal electromagnetic signal? I want a theoretical opinion about this question:
The relativistic Doppler Shift equation for the light is $$\frac{f_s}{f_o}=\sqrt{\frac{1+\beta}{1-\beta}}$$
where $\beta=v/c$ is the velocity of the observer in terms of the speed of light.
So if we assume that we have an infinite length lossless copper cable which can carry frequencies up to 10 Ghz only and this cable has a light emitter and light receiver inside.
The light emitter sends light a signal with frequency equal to 1 Thz while moving to the left in a speed very close to the speed of light and the receiver also moving to the left at the same speed.
if we chose the right velocity ($v$) for emitter & receiver then we will have a relative frequency effect such as :
1-  The original signal (light) will have frequency equal to 1 Thz.
2-  The transmitted signal through the copper cable will be red shifted and will have a reduced frequency equal to 10 Ghz.
3-  The received signal will be blue shifted and will have frequency equal to the original signal (1 Thz).
We can see here that the copper cable transmit light signal while in normal conditions it's not possible to do that.
Is it possible for the light (photons) to turns into normal electromagnetic signal?

A: Light has a frequency of approx. 1e15Hz. Can light be transmitted in a hollow copper tube? Yes. No need to go relativistic. Can objects move at near the speed of light in a coax cable with inner conductor? No. They can't move in there, at all, not even at walking speed. Does any of this has anything to do with photons? No.
Your experiment does have a "realistic" implementation. Take two observers at rest against each other and a spaceship traveling between them at relativistic speed. Communication is done with light from and to the spaceship, but because of the Doppler shift the ship receives an RF signal with a regular antenna, which it amplifies, sends from aft to stern trough a coax cable and sends out, again, trough an RF antenna. Would that work? Yes, except that one can't make such an ultra-relativistic spaceship.
The relevant related effect in real life is the ultrahigh energy cosmic ray cutoff due to CMB background photons. That one is real and it is an area of active research.