text:
Q: SQL Server LEN/DATALENGTH always returning 8000 for text column I'm working in 2008R2 currently, but I've got an audit table, tAudit, that was created in SQL Server 2000, I believe. Among others, tAudit has a text column called Change.  There's over 200k rows in tAudit.
I need to find the max length of the text contained in the Change column, but LEN and DATALENGTH both report 8000 characters for every row.  A sample of visual inspections suggests that the max length is more likely in the 200 to 300 character range.
Things I've tried:
-- All 236645 rows are 8000. What is going on here?
SELECT max(DATALENGTH(CAST(change AS VARCHAR(MAX)))), COUNT(*) AS MaxLenCount FROM dbo.tAudit
SELECT max(DATALENGTH(change)), COUNT(*) AS MaxLenCount FROM dbo.tAudit
SELECT max(LEN(LTRIM(RTRIM(CAST(change AS VARCHAR(MAX)))))), COUNT(*) AS MaxLenCount
FROM dbo.tAudit

CREATE TABLE #tAuditTemp
(
     TaskID INT
   , AuditDate DATETIME
   , CHANGE varchar(8000)
)
INSERT INTO #tAuditTemp
   SELECT
        JobID
      , AuditDate
      , Change
   FROM dbo.tAudit
   ORDER BY
        AuditDate
      , JobID
      , cast(Change AS VARCHAR(max))

SELECT max(LEN(change)) AS MaxLen FROM #tAuditTemp  -- All are 8000 again; so much for the VAR part of VARCHAR in this case.

Specifying anything less than 8000 for Change in the temp table results in a truncation error at runtime.
I've also tried using CHARINDEX to locate the end of the string, but the Change values don't have sufficient commonality in the last few characters of the string that CHARINDEX does me any good.
The table was created with ANSI_PADDING ON. Capturing some Change data from the SSMS row editor shows that trailing blanks have not been stored.
Questions:
    1. Any idea why the length of 8000 would be reported for every row?
    2. Any idea how the actual lengths of the Change data can be extracted?

A: char type is always padded with spaces to it's length (in your case 8000), you need to use varchar to prevent padding, you can also try to TRIM to get actual text
here is from http://msdn.microsoft.com/en-us/library/ms176089.aspx

char [ ( n ) ]
Fixed-length, non-Unicode string data. n defines the string length and must be a value from 1 through 8,000

or you can turn off padding

If SET ANSI_PADDING is OFF when either CREATE TABLE or ALTER TABLE is
  executed, a char column that is defined as NULL is handled as varchar.

UPDATE:
I suppose you have at least 1 row with actual length 8000, which is why max returned it, if you want to calculate number of rows with different length, you can use:
SELECT LEN(change) as ChangeLength, COUNT(*) as LengthCount
FROM dbo.tAudit
GROUP BY LEN(change)
ORDER BY 1

A: The Questions:
   1. Any idea why the length of 8000 would be reported for every row?
   2. Any idea how the actual lengths of the Change data can be extracted?

The Answers:
   1. Because I was so wrapped up in the difficulties of dealing with a TEXT field, I didn't pay attention to the fact
that the MAX was left over from the copy/paste in the three original queries at the top of this page.  Lashane's
"SELECT LEN(change) as ChangeLength, COUNT( * ) as LengthCount..."
pointed me to my (obvious) problem.
   2. Tweaking the query referenced above to use the temp table instead of tAudit allowed me to get the needed
results. Also, however, without the spurious MAX, I was also able to get the desired result directly from tAudit using
  SELECT LEN(CAST(change AS VARCHAR(MAX))) as ChangeLength, COUNT(*) as LengthCount
   FROM dbo.tAudit
   GROUP BY LEN(CAST(change AS VARCHAR(MAX)))
   ORDER BY 1 desc
Thanks to everyone who contributed!

A: There are no CHAR columns involved here.  The issue is that a TEXT column always shows a length of 8000, irrespective of the actual length of the string, and no padding spaces have been stored.  ANSI_PADDING ON allows trailing spaces to be stored, but again, that is not the case here, as none of the rows I have inspected have even one trailing space.


text:
Q: C++20 coroutines and happens-before relation Do C++20 coroutines provide some guarantees about synchronizes-with relation?
I would hope for something more or less like ``suspension synchronizes-with resumption" but that's probably too much. So far I was only able to find this statement on cppreference.com

Note that because the coroutine is fully suspended before entering awaiter.await_suspend(), that function is free to transfer the coroutine handle across threads, with no additional synchronization. For example, it can put it inside a callback, scheduled to run on a threadpool when async I/O operation completes.[...]

I also found this in [coroutine.handle.resumption]

Resuming a coroutine via resume, operator(), or destroy on an execution agent other than the one on which it was suspended has implementation-defined behavior unless each execution agent either is an instance of std::thread or std::jthread, or is the thread that executes main.
[ Note: A coroutine that is resumed on a different execution agent should avoid relying on consistent thread identity throughout, such as holding a mutex object across a suspend point.
— end note
]
[ Note: A concurrent resumption of the coroutine may result in a data race.
— end note
]

I also realize that the linked documentation of handle.resume() does not say that it happens-after some other operation. But still, the quoted statements seem to indicate that there are some synchronization guarantees, when
we pass the handle between different std::threads. So what exactly is guaranteed? [Some links to relevant fragments of the standard for further reading will be deeply appreciated.]

redpajama_set_name: RedPajamaStackExchange


text:
Q: Exit an async with in Python What I need is a way to get out of async with (line 2) if page.click (line 4) doesn't find the element, I tried with break but it didn't work, here's the code:
try:
    async with page.expect_download(timeout=120000) as download_info:
        try:
            await page.click(First_Row_Download, timeout=3000)
        except:
            break

    Download = await download_info.value
    await Download.save_as(Download.suggested_filename)
    Download_Finished = True
    break
except:
    await page.wait_for_timeout(Wait_Time) # 3 Minutos
    await page.click(Button_Refresh)

A: How about checking if the element is clickable:
https://playwright.dev/docs/api/class-locator#locator-click
use trial option and if it returns true continue execution
  await page.click(First_Row_Download, , {trial:true})


text:
Q: AWS IAM Policy for restricting access to particular groups in AWS SSO I have multiple groups in AWS SSO as in image below. Individual groups contains users of individual customer.
AWS SSO Groups
I want to create a create a custom Policy in IAM. The policy should have the below definition –
a.  Allow Add User in AWS SSO. (While adding user in AWS SSO, IAM user should be able to assign AWS SSO group to the AWS SSO user).
b.  Edit User / Delete User in AWS SSO (Restricted Access. IAM user with this policy can perform these actions for users present in his/her customer group in AWS SSO). Eg. If IAM user is for 'Test_Customer_1', then IAM user should be able to edit/delete users in AWS SSO who are present in group 'Users_Test_Customer_1' only and not users of other groups.
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "sso-directory:ListGroupsForUser",
        "sso-directory:DisableUser",
        "sso-directory:EnableUser",
        "sso-directory:SearchGroups",
        "sso-directory:DeleteGroup",
        "sso-directory:AddMemberToGroup",
        "sso-directory:DescribeDirectory",
        "sso-directory:UpdateUser",
        "sso-directory:ListMembersInGroup",
        "sso-directory:CreateUser",
        "sso-directory:DescribeGroups",
        "sso-directory:SearchUsers",
        "sso:ListDirectoryAssociations",
        "sso-directory:RemoveMemberFromGroup",
        "sso-directory:DeleteUser",
        "sso-directory:DescribeUsers",
        "sso-directory:UpdateGroup",
        "sso-directory:CreateGroup"
      ],
      "Resource": "*"
    }
  ]
}

With the custom policy defined above, IAM users with this policy will be able to manipulate users in all groups present in AWS SSO.
Is there a way to update the policy to restrict IAM user to update AWS SSO users for a particular AWS SSO group and not all groups.


text:
Q: JUnit - assertSame Can someone tell me why assertSame() do fail when I use values > 127?
        import static org.junit.Assert.*;

        ...

        @Test
        public void StationTest1() {
          ..

          assertSame(4, 4);         // OK
          assertSame(10, 10);       // OK
          assertSame(100, 100);     // OK
          assertSame(127, 127);     // OK
          assertSame(128, 128);           // raises an junit.framework.AssertionFailedError!
          assertSame(((int) 128),((int) 128)); // also junit.framework.AssertionFailedError!
        }

I'm using JUnit 4.8.1.

A: The reason is the autoboxing of Java.
You use the method:
public static void assertSame(Object expected, Object actual)

It only works with Objects. When you pass ints to this method, Java automatically calls
Integer.valueOf( int i )

with these values. So the cast to int has no effect.
For values less than 128 Java has a cache, so assertSame() compares the Integer object with itself. For values greater than 127 Java creates new instances, so assertSame() compares an Integer object with another. Because they are not the same instance, the assertSame() method returns false.
You should use the method:
public static void assertEquals(Object expected, Object actual)

instead. This method uses the equals() method from Object.

A: assertSame takes two Object arguments, and so the compiler has to autobox your int literals into Integer.
This is equivalent to
assertSame(Integer.valueOf(128), Integer.valueOf(128));

Now for values between -128 and 127, the JVM will cache the results of Integer.valueOf, so you get the same Integer object back each time. For values outside of that range, you get new objects back.
So for assertSame(127, 127), JUnit is comparing the same objects, hence it works. For assertSame(128, 128), you get different objects, so it fails.
Just another reason to be careful with autoboxing.


text: Q: How much freedom do we have when working with sequences? Consider the sequence $$a_n = \sum_{k = 1}^n \frac{1}{k} - \log(n)$$ and suppose we are to show it is Cauchy. (Do not solve the exercise for me. Spoilers are not welcome.) While there maybe are better methods, my question is the following: for $n \ge  m \ge N$, I end up with the expression as part of my calculation $$\sum_{k=m+1}^n \frac{1}{k} + \log(\frac{m}{n})$$ Am I free to say that $m$ and $n$ "grows big together", in a sense, in order to get the desired proximity to $\log(1)$?


text:
Q: Fileshare link in firefox - I have a page which renders beautifully in IE but NOT in Firefox, the fileshare link is broken in Firefox.
In the sourcecodes, I have some URL links showing as:
<html>
<body>
<form>
.....
</form>
<script type='text/javascript'>//<![CDATA[
var ctl00_ctl42_g_9097923b_f721_43d1_be88_817032f0ffd8_ctl00results={ ...
<HHUrl>file:\u002f\u002fserver\u002ffolder\u002fTraining\u002fSummit2012\u002fB105_Jeavons.pptx<\u002fHHUrl>
....};
......
// ]]></script>
</body>
</html>

I have a Jquery to replace all the file:\u002f\u002f into the *file:\u002f\u002f\u002f\u002f\u002f\u002f\u002f\u002f* as shown below:
    <script type="text/javascript">
          $(function(){
            if(!$.browser.msie) {

                var replaceFSString = $('body').html().replace(/[file:\u002f\u002f]/g,'file:\\u002f\\u002f\\u002f\\u002f\\u002f');
                $('body').html(replaceFSString);
            }
    </script>

However, it doesn't seem to be working.  Am I missing something?
Thanks for your help.
JPL

A: I changed my src from "file:\server\dir\file.txt" to "file:///\server\dir\file.txt" as a quick and dirty solution since I'm operating on an intranet page.
Research:
http://rubenlaguna.com/wp/2007/04/20/firefox-and-file-windows-unc-paths/


text:
Q: mongo: must be an instance of int not long I run the code in python 2.7 and windows 7. with mongo v4.2.3
from nut.mongo import connection
_c = connection['pandora'].contacts
_contact = _c.Contacts()
_contact['_id'] = 'duwenbin'
_contact['contact_address_data_id'] = int('170511111552051000')
_contact.save()

and show exception:
SchemaTypeError: contact_address_data_id must be an instance of int not long

but I run the same code in ubuntu 14.04 LTS, with python 2.7 , with mongo v3.2.9
the code run normally!
Can somebody tell me why? I think the difference is the mongo version.
But I am not sure.
Thanks!

A: 32-bit systems and 64-bit systems have different int sizes.  To verify where int stops and long begins you can check the sys.maxint value on both your ubuntu server and your windows local machine.  For example, on my 64-bit machine, sys.maxint is 9223372036854775807 (which is 2^63 - 1 since sys.maxint is the maximum signed int).  Of course, you can also switch to python3 where there is no longer an int and just a long.


text:
Q: Pushwoosh - Broadcast push notifications We're having a small issue when sending broadcast push notifications
to all ios devices, for some reason, only iPads are receiving the
notifications.
We are using the 'Send Push' section of the admin panel to do this, we
haven't configured anything specifically. Additionally, the app is a
'for iphone' app, so the ipads are running the same app as the iphone
versions.
All devices are receiving custom notifications when sent via the rest
service, the issue only occurs when using the site admin panel.
Any ideas?
Thanks in advance,
Bav

A: Did you tried StreetHawk? It pushes to iPhone/iPad, and Android as well. It has self-defined push type, meanwhile support your own customized json push. Check http://streethawk.com/.


text:
Q: What type of interpreter were most 8-bit BASIC implementations? I'm a big fan of early/mid 1980s personal computers like the Amstrad CPC, Commodore 64 and the Sinclair Spectrum. One thing these computers all had was a version of BASIC.
As a language hacker myself I'm curious: were these interpreters implemented as tree-walker interpreters (simply traversing the parse tree) or bytecode interpreters? I can't find a lot of information on how they were implemented. It's fascinating to me how they were built given the limitations of the hardware at the time.

A: They were mostly token based. This means, that the integrated code editor transformed the human readable commands in the source into a bytecode. Upon execution those bytecodes were read and a dispatcher then executed the appropriate command (stored as machine code in the kernal) with the given parameters.
The ZX Spectrum even had a keyboard to enter Basic Tokens:
http://www.worldofspectrum.org/ZX81BasicProgramming/
For some others see here:
https://www.primidi.com/atari_basic/description/the_tokenizer
http://fileformats.archiveteam.org/wiki/Commodore_BASIC_tokenized_file
http://cpctech.cpc-live.com/docs/bastech.html
Hope this anwers your question.


text:
Q: shader graph messes up the texture (Unity 2D) i am trying to make a glow shader but. when i add that _MainTex property this happens:-
shaded
shaded wireframe
I tried changing the mesh type to full rect but when i do that this happenfull rect mesh types :-
I don't know whats the problem plzz help , i am new to shader graph and i am using "sprite shader graph unlit" i also tried with but same problem . here's my shader graph :-shader Graph

A: The Sample Texture 2D node returns a vec4, but your Fragment output only accepts a vec3 and thus ignores the alpha information.
If you want the shader to also use the alpha values of your texture, you should plug the A output of the Sample Texture 2D node into the Alpha input of the Fragment.
You are currently returning the color values of the texture for all pixels and not filtering by alpha.
If this does not work, check if you have to enable translucency for the shader.


text:
Q: Como transponer un dataframe en Pandas Tengo la siguiente inquietud
Tengo el siguiente dataframe :

El cual debo transponer, para ello lo estoy haciendo de la siguiente manera:
df = dfs.transpose( )

obteniendo el siguiente resultado:

Pero como se observa en la imagen, me estan quedando los índices como titulos, y quisiera que mis titulos sean: "DESCRIPTIVA", "Aceite de palma, crudo" , "Aceites vegetales, refinados" y "Margarina y preparaciones"
Me pueden ayudar por favor como mejorar el código, para obtener el resultado deseado.  Muchas gracias por la ayuda :)

A: Gracias al comentario de @Christian, explore la opción de pivot_table y me funciono, lo hice de a siguiente manera:
cree una lista con las columnas (ya que son muchas)
columnas = dfs.columns.values[1:]

[1:] con esto obtengo los valores exceptuando la columna, que requiero transponer, para este caso DESCRIPTIVA
Finalmente ya con la lista, hago lo siguiente:
df = pd.pivot_table(dfs, columns='DESCRIPTIVA', values=columnas).reset_index()

Y asi logro obtener el dataframe como lo necesito.


text:
Q: code of model selection in rapidminer mo I was watching this video about automatic model selection in rapidminer, but the video resolution is quite low and there's no code provided. Could somebody tell me where I can find some code of similar functionality please? Thanks

A: There are some examples shipped with RapidMiner Studio. Whilst these are not quite the same as the video, they are relatively close.
In particular, //Samples/processes/06_Meta/05_OperatorEnabler, but also others in the 06_Meta folder.


text:
Q: Loop on array of arrays - Angular I'm getting an array of arrays from a service and i want to display case [0] and [1] on each iteration, but when I do that i get an error TypeError: Cannot read properties of undefined (reading '0')
      <ng-container
                *ngFor="let done of this.launch.doneAreas; index as i">

                  Case n° {{ i + 1 }} => ({{ done[i][0] }},{{ done[i][1] }})

      </ng-container>

The array is defined like this in the service:
  doneAreas: any[][] = [];

and I'm pushing values by pushing an array of numbers into it. coords beeing an array of two numbers.
  this.doneAreas.push(this.coords);

Here's an example of the array i want to display when I console.log it.
0: (2) [3, 3]
1: (2) [3, 4]
2: (2) [4, 4]
3: Array(2)
0: 4
1: 3
length: 2
[[Prototype]]: Array(0)
Thanks

A: You could make a dynamic object {x: number, y: number}. If you use that in a list you can ensure both should be present.
Your issue is that done already is an object and you are trying to get the index of an array that is not present.
doneAreas: {x: number, y: number}[] = [];

this.doneAreas.push({this.coords.x, this.coords.y);

<ng-container
          *ngFor="let done of this.launch.doneAreas; index as i">

            Case n° {{ i + 1 }} => ({{ done.x }},{{ done.y }})

</ng-container>

If you want to keep the code as it is you should just remove [I]:
      <ng-container
                *ngFor="let done of this.launch.doneAreas; index as i">

                  Case n° {{ i + 1 }} => ({{ done[0] }},{{ done[1] }})

      </ng-container>


text:
Q: Google Sheets: Internal Error Executing Custom Function I am creating a custom function in Google Spreadsheet's script editor, let me present the code first:
function customFunction(input_array) {
var sorted = input_array.slice().sort(function(a,b){return a-b})

bins = []
var initial = sorted[0]
var final = sorted[sorted.length - 1]

while (initial < final) {
    initial += 0.03
    bins.push(initial)
    }

return bins

}

So basically, the variables "initial" and "final" are the problematic ones. Because if I change these variables to specific numbers, instead of the array index that I have here, the function works.
How do I resolve this for implementation in Google Sheets?
Thanks in advance!


text:
Q: Do not allow detach for one bash I would like to know if it's possible to forbid all detached-like things for a given shell.
More precisely, I'd like to make sure that if a command runs in a specific shell, when the command stops, all the children spawn by that command are deleted, no matter what command does (including running a new screen, detach...). That way, I want to make sure that if the command:
ps -O stat --ppid <my bash ppid>

does not output anything, then there is no remaining process on my computer ran by a given user.
Is it possible without using containers?


text:
Q: Airflow: Get trigger date of DAG Airflow I schedule my DAGS daily but some dags run for 2,3 days also I have set max_active_runs=1 which means exactly one dag will run at a time and other will be queued.
So is there a way to get exactly when my DAG was triggered and was queued?

A: You can get this info from scheduler logs.
Search for DAG name and you will find state change and picking up DAG by scheduler.


text:
Q: Notifications that open by themselves the notifications of my app open without a logical sense than the code that I wrote. I should receive a notification every day at the same time but if I open the app I get the same notification. This is the code in MainActivity:
public void setRepeatingAlarm() {
         Intent intent = new Intent(this, MyAlarmService.class);
         PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,
         intent, PendingIntent.FLAG_CANCEL_CURRENT);
         Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.HOUR_OF_DAY, 13);
            calendar.set(Calendar.MINUTE, 00);
            calendar.set(Calendar.SECOND, 00);

         am.setRepeating(AlarmManager.RTC_WAKEUP,  calendar.getTimeInMillis(),24*60*60*1000,pendingIntent);
}

And this is MyAlarmService:
public class MyAlarmService extends BroadcastReceiver {

 NotificationManager nm;

 @Override
 public void onReceive(Context context, Intent intent) {
  nm = (NotificationManager) context
    .getSystemService(Context.NOTIFICATION_SERVICE);
  CharSequence from = "Locali Torino";
  CharSequence message = "Visita le serate!";
  Intent action = new Intent(context, MainActivity.class);
    PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
    action, 0);

  Notification notif = new Notification(R.drawable.disco,
    "Visita le serate!", System.currentTimeMillis());
  notif.setLatestEventInfo(context, from, message, contentIntent);
  notif.flags |= Notification.FLAG_AUTO_CANCEL;
  nm.notify(0, notif);

 }
}

Why I get notifications when I open the app or at least not only at the set time?
EDIT
MyAlarmService:
public class MyAlarmService extends BroadcastReceiver {

 NotificationManager nm;

 @Override
 public void onReceive(Context context, Intent intent) {

  nm = (NotificationManager) context
    .getSystemService(Context.NOTIFICATION_SERVICE);
  CharSequence from = "Locali Torino";
  CharSequence message = "Visita le serate!";
  Intent action = new Intent(context, MainActivity.class);

    PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
    action, 0);

  Notification notif = new Notification(R.drawable.disco,
    "Visita le serate!", System.currentTimeMillis());
  notif.setLatestEventInfo(context, from, message, contentIntent);
  notif.flags |= Notification.FLAG_AUTO_CANCEL;
  nm.notify(0, notif);
  SharedPreferences mPref = context.getSharedPreferences("pref_name", Context.MODE_PRIVATE);
    SharedPreferences.Editor mEditor = mPref.edit();

    long time = System.currentTimeMillis();
    mEditor.putLong("UPDATE_TIME", time);
    mEditor.commit();
 }And this is MainActivity:

public void setRepeatingAlarm() {
         Intent intent = new Intent(this, MyAlarmService.class);

         PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,
         intent, PendingIntent.FLAG_CANCEL_CURRENT);

         long startAt;
         long period;

         SharedPreferences mPref = context.getSharedPreferences("pref_name", Context.MODE_PRIVATE);

         long dif = System.currentTimeMillis() - mPref.getLong("UPDATE_TIME", 0);

         if (dif >= UPDATE_PERIOD) {
           startAt = 0;
           period = UPDATE_PERIOD;
         } else {
           startAt = dif;
           period = dif;
         }

         am.setRepeating(AlarmManager.RTC_WAKEUP, startAt, period,pendingIntent);
}

A: The service runs when you register it, so what you need to do is pass a boolean value with the intent when registering the service to prevent it from running when the application runs, but to run periodically thereafter.
In your activity add:
intent.putExtra("run", false);

Then in MyAlarmService:
private boolean run = true;
// ...
action.getBooleanExtra("run", run);
if(run) {
    // notifications code
} else {
    run = true;
}

A: Actually it works exactly as code is written. The cause of that behavior is your startAt parameter in setRepeating method.
 am.setRepeating(AlarmManager.RTC_WAKEUP,
                 calendar.getTimeInMillis(),
                 24*60*60*1000,
                 pendingIntent);

calendar.getTimeInMillis() time in milliseconds that the alarm should first go off, using the appropriate clock (depending on the alarm type).
For example :
//send first alarm after 1 second and repeat it every 24 hours
am.setRepeating(AlarmManager.RTC_WAKEUP,
                 1000,
                 24*60*60*1000,
                 pendingIntent);

//send first alarm after 10 second and repeat it every 24 hours
am.setRepeating(AlarmManager.RTC_WAKEUP,
                 10000,
                 24*60*60*1000,
                 pendingIntent);

UPDATE :
You need to save your last update time :
public class MyAlarmService extends BroadcastReceiver {

 NotificationManager nm;

 @Override
 public void onReceive(Context context, Intent intent) {
  //send alarm here
  //...

    SharedPreferences mPref = context.getSharedPreferences("pref_name", Context.MODE_PRIVATE);
    SharedPreferences.Editor mEditor = mPref.edit();
    mEditor.putLong("UPDATE_TIME", time);
    mEditor.commit();
 }
}

Then you can make your setRepeatingAlarm method like this :
public void setRepeatingAlarm() {
         Intent intent = new Intent(this, MyAlarmService.class);
         PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,
         intent, PendingIntent.FLAG_CANCEL_CURRENT);

         long startAt;
         long period;

         SharedPreferences mPref = context.getSharedPreferences("pref_name", Context.MODE_PRIVATE);

         long dif = System.currentTimeMillis() - mPref.getLong("UPDATE_TIME", 0);

         if (dif >= UPDATE_PERIOD) {
           startAt = 0;
           period = UPDATE_PERIOD;
         } else {
           startAt = dif;
           period = dif;
         }

         am.setRepeating(
               AlarmManager.RTC_WAKEUP,
               startAt,
               period,
               pendingIntent);
}


text:
Q: beautifullsoup between br tag I am trying to scrap from the (span class= 'Number'). The code looks like this on the pages I am scrapping:

99 10.00    (-0.1%)
Menu

Max Quantity

100.000

Average Quantity

822

Previous Order

96

Max Price

104

Number of Trades

383

Min Price

59

Total Amount

800

Start

10

Low

98

I have tried to use Beautifulsoup to scrape the data. However, it returns Nothing on the screen
 from bs4 import BeautifulSoup

 html = response.content
 soup = BeautifulSoup(html,"html.parser")
 title =  soup.select('td.styleB')[0].next_sibling
 title1 = soup.find_all('span', attrs={'class': 'Number'}).next_sibling
 print(title1)

I am hoping that I could retrieve the number as follows:
Max Quantity: 100
Average Quantity: 822
Previous Order: 96
Max Price: 104
Number of Trades:383
Min Price: 59
Total Amount:800
Start:10
Low: 98
Please advise what is the problem with my code from handling the query. Thank you

A: The possible solution is as follows - dig into bs4 more, you may get to a more efficient and elegant solution:
from bs4 import BeautifulSoup

soup = BeautifulSoup(open("bs4_test.html"), "html.parser")
tds = soup.select('td.styleB')
for td in tds:
    num = td.select('span.Number')
    for i in num:
        print ("{0} : {1}".format(td.next_element, i.string))

The bs4_test.html is the html you shared - the above lines output:
Max Quantity : 100.000
Average Quantity : 822
Previous Order : 96
Max Price : 104
Number of Trades : 383
Min Price : 59
Total Amount : 800
Start : 10
Low : 98

The bs4_test.html for reference:
<!DOCTYPE html>

    <title></title>

                99 10.00 (-0.1%)
                Menu
                Max Quantity

                100.000
                Average Quantity

                822
                Previous Order

                96
                Max Price

                104
                Number of Trades

                383

                Min Price

                59
                Total Amount

                800
                Start

                10
                Low

                98


text:
Q: How to find smallest and largest "cells" on these images? I have the task to first find all "cells" on images using Python, then count them and last but not least find the smallest and largest of these cells/areas. On such image could look like this:

The bright areas are the "cells" to identify, the black lines and areas are gaps in between. I was trying to find a solution to this problem with OpenCV's findContours() function, but I wasn't able to correctly find all lines between those cells, e.g. the very thin one in the lower left corner. Moreover, how could I filter out only the bright cells with this approach and ignore the black gaps in between?


text:
Q: Field of characteristic $0$ and simple roots Suppose $g(x)=f(x)m(x)^{-1}$ where $f(x)\in F[x]$ and $F$ has characteristic $0$ and $m(x)=(f,f')$. Then show that all roots of $g(x)$ are simple.
I assume g(x) has multiple roots that is $g(x)=(x-s)^nh(x)$ and after computing the derivative I concluded $(x-s)|g'(x)$. Then I consider $g(x)=fm^{-1}$ and use the fact that $f(x)=m(x)a(x)$ and $f'(x)=m(x)b(x)$. I rewrite $g'(x)=f(x)m(x)^{-2}+f'(x)m(x)^{-1}$. From this I want to conclude that the right hand side is not divided by $(x-s)$ but I am stuck at this part.

A: We'll assume for simplicity that $f$ is monic. Factor $f(x)$ in an algebraic closure as $(x-r_1)^{n_1}\cdots(x-r_k)^{n_k}$, where the $r_i$'s are distinct roots. You can check that $f'$ is divisible by $(x-r_1)^{n_1-1}\cdots(x-r_k)^{n_k-1}$. This product should be $m(x)$, and since $F$ has characteristic $0$, $m(x)\neq 0$ (assuming $f$ is nonconstant). But proving it's exactly equal to $n(x)$ is unnecessary; we just need that $m\mid f$ and $m$ is a multiple of the product above. Then, $f/m$ will be a factor of $(x-r_1)\cdots (x-r_k)$, which has every root with multiplicity $1$.


text:
Q: "We're sorry, a server error occurred. Please wait a bit and try again" while creating charts We are running into sporadic errors (more often than not) on a project that generates Google Doc documents based on info entered into Google Sheet spreadsheets.
The Google Apps Script project pulls data (from sheets), caches it in-memory with standard var statements, massages the data a bit (formatting, de-duping, etc), then copies a Doc template and does a bunch of token substitution and also inserts some charts based on the in-memory variables.
We are encountering the following error during a high quantity of executions:
Exception: We're sorry, a server error occurred. Please wait a bit and try again.
    at insertChart(Code:5890:10)
    at processForm(Code:4540:5)

The main method creates several (between 5 - 20 or more) charts depending on parameters entered at run-time by the user (which happens via a standard Web Form created by GAS:
function doGet() {
  return HtmlService
      .createTemplateFromFile('index')
      .evaluate();
}

The web page returned by the above is a very standard GAS HTMLService webapp. It contains a form that allows a user to select a few standard types of reporting criteria (date range, filter by certain types of data, etc).
We are duplicating a "template" Docs file which has a bunch of common text and some tokens that we use as placeholders to find and replace with data loaded from the Sheets. The Sheets are very common spreadsheets with the kind of data you'd imagine: date ranges, selections from drop-down lists, free-text columns, etc. (The filtering info specified by the user is used to query the Sheets for the data we want to "merge" into the new Doc. It's basically a much more complex version of your standard "mail merge".)
  var templateId = 'asdfasdfasdfasdfasdfasdfasdfasdfasdf'; // DEV
  var documentId = DriveApp.getFileById(templateId).makeCopy().getId();

  DriveApp.getFileById(documentId).setName('Demo Report - Project Report');
  DriveApp.getFileById(documentId).setSharing(DriveApp.Access.ANYONE_WITH_LINK, DriveApp.Permission.COMMENT);

  Logger.log('templateId: ' + templateId);
  Logger.log('documentId: ' + documentId);

  var doc = DocumentApp.openById(documentId);
  var body = doc.getBody();

We have the following method which takes the Doc body, placeholder, and formatted data from a chart builder. It then identifies the Doc element token to replace (simply a string in the Doc file), and runs a body.insertImage after that token element.
function insertChart(body, placeholder, chart) {
  if (placeholder.getParent().getType() === DocumentApp.ElementType.BODY_SECTION && typeof chart !== 'undefined' && chart !== null) {
    var offset = body.getChildIndex(placeholder);

    //Logger.log(chart);

    body.insertImage(offset + 1, chart);
  }
}

We have several helper methods like the following buildStackedColumnChart(). It's meant to wrap the Chart API commands to use a dataTable and Chart Builder to return a specific type of chart (bar, stacked bar, line, etc).
Its resulting chart gets passed into the insertChart() method above.
function buildStackedColumnChart(title, header, data) {
  Logger.log('buildStackedColumnChart');
  Logger.log('title: ' + title);
  Logger.log('header: ' + header);
  Logger.log('data: ' + data);

  try {
    var dataTable = Charts.newDataTable();

    for (var hr = 0; hr < header.length; hr++) {
      var headerRow = header[hr];

      dataTable.addColumn(headerRow[0], headerRow[1]);
    }

    for (var r = 0; r < data.length; r++) {
      var row = data[r];

      dataTable.addRow(row);
    }

    dataTable.build();

    var chart = Charts.newColumnChart()
      .setDataTable(dataTable)
      .setDimensions(600, 500)
      .setTitle(title)
      .setStacked()
      .build();
    return chart;
  } catch (ex) {
    Logger.log('ex: ' + ex);
    return null;
  }
}

In the main processForm() method (called directly by the webapp menioned above when the user selects their criteria and clicks a "Generate Report" button. We have a few calls to a method which finds the token in the template file (just text with {{}} around it as shown below). It iterates through a hard-coded list of values in the in-memory data variables storing accumulations from the Sheets and creates chartHeader and chartData (which contains the values to be charted in a mechanism the helper methods above can translate back into calls that make sense for the Chart API) and uses the insertChart() and `` helper methods to insert the chart after the bookmark token and then remove the bookmark from the document (cleanup so the tokens aren't present in the end report Doc).
  var chartTrainingsSummaryBookmark = findPlaceholder(body, '{{CHART_TRAININGS_SUMMARY}}');

  Logger.log('chartTrainingsSummaryBookmark: ' + chartTrainingsSummaryBookmark);

  var chartCategories = [
    'Call',
    'Conference Attendee',
    'Meeting (External)',
    'Partnership',
    'Quarterly Board Meeting',
    'Alliance or Workgroup',
    'Training (Others)',
    'Training (Professional Development)',
    'Youth Training',
    'Webinar or Zoom',
    'Other',
    'Coalition',
    'Email',
    'Face-to-face',
    'Phone',
    'Site Visit',
  ];

  //  {Call=10.0, Conference Attendee=10.0, Quarterly Board Meeting=10.0, Alliance or Workgroup=10.0, Coalition=10.0, Meeting (External)=10.0}

  var chartHeaderData = [];
  var chartData = [];

  var monthChartHeader = [[Charts.ColumnType.STRING, 'Month']];
  var monthChartData = [monthName];
  for (var cci = 0; cci < chartCategories.length; cci++) {
    var chartCategory = monthName + ':' + chartCategories[cci];

    if (getChartData(chartCategory, trainingsChartData) > 0) {
      monthChartHeader.push([Charts.ColumnType.NUMBER, chartCategory.split(':')[1]]);
      monthChartData.push(getChartData(chartCategory, trainingsChartData));
    }
  }
  if (monthChartData.length > 1) {
    if (chartHeaderData.length < 1) {
      chartHeaderData = chartHeaderData.concat(monthChartHeader);
    }
    chartData.push(monthChartData);
  }

  Logger.log('----- CHART - TRAININGS: SUMMARY -----');

  if (chartData.length > 0 && chartData[0].length > 1) {
    insertChart(body, chartTrainingsSummaryBookmark, buildStackedColumnChart('', chartHeaderData, chartData));
  }
  chartTrainingsSummaryBookmark.removeFromParent();

We are also seeing slight variations that also error out the document generation with a Timeout. (This process can take a while if there is a lot of data that fits within the parameters which the user specified.)
We were wondering why these errors would happen on a seemingly random interval. We can literally just click the button that makes the call again and it might work, or might error out on a different chart, etc.
This script has been working for the most part (we did encounter a few specific errors) in months previous; however, this "Exception: We're sorry, a server error occurred. Please wait a bit and try again." started occuring last weekend and got far worse on Monday / Tuesday (nearly every execution failed, very few succeeded). It's not happening quite as badly today; but we are seeing a few errors.
Also, it's a bit strange, but copying the GAS Project and executing the copy has thrown the error less frequently than the original project in production.
We have some ideas for workarounds; bu, ideally, we would like to identify a root cause so we can correctly fix the issue.


text:
Q: Mysql double to datetime I have a row of dates that are stored as double 778867200000 and I now need to convert them  to datetime. I don't want to try to convert them in the same row just in case it goes wrong. Therefore I've added a new row and default is NULL.
I've tried a few combinations to achieve what I'm looking for  but with no luck.
Here's the type of thing I've been trying...
 UPDATE daily_quotes t, (SELECT DISTINCT id, date
                    FROM daily_quotes
                   WHERE id BETWEEN 1 AND 5) t1
SET t.unix_date = CONVERT(t1.date, DATETIME)
WHERE t.id = t1.id

Can anybody offer a solution?
Thanks
Steve
PS: I'm just restricting it to 1-5 for testing  purposes. I actually have over 300k records.

A: Assuming your double is supposed to be in Unix epoch time, you'll want to use the MySQL function FROM_UNIXTIME().
SET t.unix_date = FROM_UNIXTIME(t1.date)

Since your timestamps have three more digits than they should, you can trim them with substring or divide by 1000 as pointed out by Schwern.
SUBSTRING(t1.date, 1, length(t1.date) - 3)

is equivalent to:
FLOOR(t1.date/1000)

You could also:
ROUND(t1.date/1000)

Rounding may be necessary if FROM_UNIXTIME doesn't support fractions.
So all together:
SET t.unix_date = FROM_UNIXTIME(SUBSTRING(t1.date, 1, length(t1.date) - 3))


text:
Q: Hierarchical Router Django Rest So I have a Django project in which each app manages some type of a data table. Thus all of them follow a similar format in which there is a Table and Item model, each with an accompanying serializer and viewset. I'd like my apps to function such that there is no naming conflict between models of the same name in different apps. I would also like the router to act in a hierarchy first listing all the apps in the renderer in the form of /api/{app} and once you click it will give you the viewsets such as:
/api/{app}/table

/api/{app}/item

I've tried playing around with DefaultRouter and SimpleRouter but couldn't really managed to get anything to work properly.

A: I think what you need is a "Nested Router" which is available as a PyPi package (it's recommended in official DRF documentation in the Third Party Packages section).
In a shortcut you may use it in the following manner (docs):
/domain/ <- Domains list
/domain/{pk}/ <- One domain, from {pk}
/domain/{domain_pk}/nameservers/ <- Nameservers of domain from {domain_pk}
/domain/{domain_pk}/nameservers/{pk} <- Specific nameserver from {pk}, of domain from {domain_pk}

In your case code would look like:
from rest_framework_nested.routers import NestedSimpleRouter

router = DefaultRouter()
router.register(r'app', AppViewSet, basename='app')

app_router = NestedSimpleRouter(router, 'app', lookup='app')
app_router.register(r'table', TableViewSet, basename='table')
app_router.register(r'item', ItemViewSet, basename='item')

And then you must override get_queryset() method:
class TableViewSet(viewsets.ModelViewSet):
    def get_queryset(self):
        return Table.objects.filter(
            app=self.kwargs.get('app_pk'),
        )


text:
Q: Getting SUM of 2 different table from another table I'm working on a expenses/budgeting tracking system and stuck in some part.
I have 4 tables
tblProjects

tblCategory

tblExpenses

tblIncomes

tblProjects relate to tblCategory with 1:1,
tblExpenses relate to tblProjects also with 1:1,
same goes for tblIncomes which relate to tblProjects with 1:1

I'm trying to get the sum of expenses and incomes of each category group by the year(from column tblProjects.proj_sdate), plus a column that will show the P&L(expenses - incomes).
For instance I want to know what is the total amount of expenses, total amount of incomes, the value of P&L spent for Trip, Sports etc.
Below example of what I want to achieve;

I managed to come up with 2 query below which separate the incomes and expenses. But not sure how to combine it making it single query and perform the subtraction as well to get the P&L value.
1)Incomes
SELECT category.cat_title as Category, group_concat(distinct
projects.proj_title) as Projects, date_format(projects.proj_sdate, '%Y') as
Year, sum(incomes.inc_amount) as Total_Incomes from category inner join
projects on projects.proj_cat = category.cat_id inner join incomes on
incomes.projects_id = projects.proj_id group by category.cat_title,
date_format(projects.proj_sdate, '%Y')

2)Expenses
SELECT category.cat_title as Category, group_concat(distinct
projects.proj_title) as Projects, date_format(projects.proj_sdate, '%Y') as
Year, sum(expenses.exp_amount) as Total_Expenses from category inner join
projects on projects.proj_cat = category.cat_id inner join expenses on
expenses.projects_id = projects.proj_id group by category.cat_title,
date_format(projects.proj_sdate, '%Y')

A: I think this query will give you the results you want. Because you can have multiple expense and income lines per project, you need to JOIN to summed tables of incomes and expenses (by project) rather than the raw table. The results of all the JOINs are then grouped by Category and Year:
SELECT c.cat_title AS Category,
       GROUP_CONCAT(p.proj_title) AS Projects,
       YEAR(p.proj_sdate) AS Year,
       COALESCE(SUM(i.income), 0) AS Total_Income,
       COALESCE(SUM(e.expenses), 0) AS Total_Expenses,
       COALESCE(SUM(i.income), 0) - COALESCE(SUM(e.expenses), 0) AS `P&L`
FROM tblCategory c
JOIN tblProjects p ON p.proj_cat = c.cat_id
LEFT JOIN (SELECT projects_id, SUM(exp_amount) AS expenses
           FROM tblExpenses
           GROUP BY projects_id) e ON e.projects_id = p.proj_id
LEFT JOIN  (SELECT projects_id, SUM(inc_amount) AS income
           FROM tblIncome
           GROUP BY projects_id) i ON i.projects_id = p.proj_id
GROUP BY Category, Year

Results (for the sample data in your question):
Category    Projects                    Year    Total_Income    Total_Expenses  P&L
KSS Talks   Projects XYZ                2017    2.00            152.00          -150.00
KSS Talks   Projects X,Projects Satu    2018    371.00          365.00          6.00
Sports      Projects Y                  2018    150.00          0.00            150.00
Trip        Projects Z                  2018    15.00           0.00            15.00

Demo on dbfiddle

A: You can try below
SELECT category.cat_title as Category, group_concat(distinct
projects.proj_title) as Projects, date_format(projects.proj_sdate, '%Y') as
Year, sum(incomes.inc_amount) as Total_Incomes,
sum(expenses.exp_amount) as Total_Expenses,
sum(incomes.inc_amount) -  sum(expenses.exp_amount) as PL
from category inner join projects on projects.proj_cat = category.cat_id
inner join expenses on expenses.projects_id = projects.proj_id
inner join incomes on incomes.projects_id = projects.proj_id
group by category.cat_title,
date_format(projects.proj_sdate, '%Y')


text:
Q: PayPal Developer App/APi Credentials I am creating a PayPal gateway for a store/shopping cart created for a CMS. Once completed, the gateway will be made available to others.
Do the API credentials (Client ID and Secret) created in my Developer account stay with the app or will everyone who uses my app be required to have API credentials of their own?

A: Everyone will need to supply their own client ID and secret.  The client ID and secret point to your PayPal account, so it's not a good idea to include those in your app.


text:
Q: How to provide car resources in Android I'm struggling with android car mode. I'm trying to create simple app that will use different layouts for normal mode and for car mode.
Android provides a method UiModeManager.enableCarMode which according to documentation should force the phone to car mode. Documentation also states that there can be resources with -car suffix. (http://developer.android.com/guide/topics/resources/providing-resources.html)
Bringing this together, I would expect, that the framework will use different resources when car mode is enabled and different when it is disabled.
However I've made a very simple prototype and it is not working. I have only one activity with layout activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:tools="http://schemas.android.com/tools"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="#0bbbff">

    <TextView
        android:text="@string/car_mode"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"/>

</RelativeLayout>

TextView has a text attribute @string/car_mode which is defined in res\values\strings.xml and also in res\values-car\strings.xml.
When I'm switching car mode on and off with UiModeManager, the text doesn't change.
Any suggestions? Thanks.

A: Ok, I've found the "solution". Apparently -car suffix only works with -land suffix.
When my folder is values-land-car instead of values-car the layout looks as it should. Of course there is no notion in documentation that car mode works only in landscape, good work guys.


text:
Q: how to retrieve date field regardless year in mysql I want to retrieve date from mysql database regardless year,
you thing we have 3 recrod
2015-4-4
2018-4-4
2009-4-5

I want to retrieve any date that has *-4-4 ,
any idea?

A: select * from your_table
where day(date_column) = 4
and month(date_column) = 4

A: You can make use of date_format() function
select *
from Table1
where date_format(date ,'%m-%d') ='04-04'

Fiddle Demo


text:
Q: Округление значения поля с шагом в 0.5 Здравствуйте! Есть числовое поле с установленным минимальным и максимальным значениями и шагом в 0.5. Подскажите пожалуйста, как округлять введенные значения в соответствии с шагом.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="number" min="0" max="5" step="0.5" placeholder="1">

A: Как-то так:

var input = document.querySelector('input[type = number]');
var inputValue;
var decimal = 1;

input.addEventListener('change', function(e){

  if(e.target.value % 1 == 0){
   decimal = 0;
  } else {
   decimal = 1;
  }

  inputValue = (Math.round(e.target.value * 2) / 2).toFixed(decimal);
  e.target.value = inputValue;
})
<input type="number" min="0" max="5" step="0.5" placeholder="1">


text:
Q: Loading images(require) doesn't work using string variable Requiring image with string variable doesn't work:
// working
var texture = require('./images/imag_01.jpg');

// doesn't work
path = './images/imag_01.jpg';
var texture = require(path);

// Error: Cannot find module "."

A: require doesn't accept a variable.
But you can do so with a dynamic import() statement should you need to import dynamically, if you are using ES6.
* Update: 2018.11.19 *
React v16.6 introduced React.lazy, which you can use to split code more easily.

A: It is not your fault, it is how it is, unfortunatetly, supposed to work. You must write require('image-path') and cannot have a variable inside the parenthesis.
See: https://facebook.github.io/react-native/docs/images.html

A: This worked for me:
var image_name = 'imag_01.jpg';
var texture = require('./images/'+image_name );


text:
Q: Is there a way to send a TimeOut object from a step to an other in a dialog? - botBuilder v4 - Node.js In one of my bot's dialog steps I'am lanching some operations in a setTimeout() function.
The goal is to clear that TimeOut in an other step in some conditions.
async saveAdults(step) {
    if (step.result) {
      step.values.adults = step.result;
      const convId = step.context.activity.conversation.id;
      const format = "dddd DD MMMM YYYY";

      // Send partial notification in case of a delay of 5 minutes
      const data = {
        checkIn: step.values.checkIn,
        nights: step.values.nights,
        adults: "",
        children: ""
      };
      const timer = await sendPartialNotification(convId, data);
      // step.values.timer = timer;
      this.notificationProp.set(step.context, timer);
      await this.conversationState.saveChanges(step.context);
    }
    return await step.next();
  }

exports.sendPartialNotification = async (convId, data) => {
  const interval = 300000;
  const timer = setTimeout(() => {
    notify(convId, this.id, data, true);
  }, interval);
  return timer;
};

async notifyClient(step) {
  const timer = this.notificationProp.get(step.context);
  clearTimeout(timer);
  // …
}

Trying to store the TimeOut object in step.values.timer or in the conversation state throws this error that indicates that it is not possible to parse the Timeout Object ...
TypeError: Converting circular structure to JSON

As solution to this, I was thinking about storing the timer in Redis ..
Is there any ideas? Thanks.

A: Use state, props, or equivalent to pass the value from one step to the next. In my example code below, I include a middle step asking if the client would like to cancel. This is purely for displaying output for the solution.

*

*Initiate the timer in a lead step.

async setTimer(step) {
  if (step.result) {
    const convId = step.context.activity.conversation.id;

    const data = {
      value1: someValue1,
      value2: someValue2
    };

    const timer = await sendPartialNotification(convId, data);

    this.notificationProp = { step: step.context, timer: timer };
    await this.conversationState.saveChanges(step.context);
  }
  return await step.next();
}

*Ask the client, in an intermediary step, if they would like to cancel the timer. I have the timer set for 10 secs.

*

*If the user cancels, the timer is cleared.

*If the client declines or fails to respond before 10 secs is up, the timer is unaffected and executes.

async askClient(step) {
  const timer = this.notificationProp.timer;

  if (timer._idleTimeout > 0) {
    const message = MessageFactory.text(
      'Cancel the timer?',
      null,
      'expectingInput'
    );
    return await step.prompt('confirmPrompt', message);
  }
}

*Lastly, output results and notify the client.

async notifyClient(step) {
  const stepResult = step.result;
  step.value = { timer: this.notificationProp.timer };

  if (stepResult === true) {
    console.log('TIMER PRE-CLEAR ', step.value.timer);

    const timer = step.value.timer;
    await clearTimeout(timer);

    console.log('TIMER POST-CLEAR', timer);
    step.context.sendActivity('Cancelling timer');
  } else {
    step.context.sendActivity('Timer not cancelled');
  }

  return await step.next();
}

Timer not cancelled and executes:

Timer cancelled:

Hope of help!


text:
Q: PHP: clearstatcache() not working My workflow is pretty simple:

*

*I delete a file

*I call clearstatcache()

*I save a new file

*I call clearstatcache()
Still, at the end, is_file() returns false for a while before deciding to return true when i refresh 10sec later for example.
It looks like a cache problem, doesn't it?
Here's a piece of my code:
// step 1
$path = 'file_to_delete.jpg';
unlink($path);

// is_file($path) returns false here -- normal behavior
// step 2
clearstatcache();

// step 3 -- some stuff going on on an uploaded image, that leads to:
imagejpeg($imagetosave, $path, 80);

// step 4
clearstatcache();

// is_file() returns false, i have to wait a couple of seconds before it starts returning true

Thank you for your help!
EDIT:
Given all the answers i had, the problem doesn't seem to come from clearstatcache().
But should i add, when i overwrite the file (thus its existing status doesn't change), is_file() returns the good result. but when its existing status actually changes, the problem happens. It would be weird if the error didn't come from clearstatcache(), right? (or something related to this cache indeed)

A: I agree with @hakre, check the result of the create/delete.
It's not quick-and-dirty, even Rasmus himself recommends it:

[2011-03-31 08:34 UTC] rasmus@php.net
You guys realize that the stat cache is per-request, right? You only
  need to  clear the stat cache before a file_exists() call if you A.
  did a stat for it, and  B. either created or deleted it on that
  request. In which case you shouldn't need  to stat it again since the
  success status of the create/delete will tell you  whether the file is
  there or not. Perhaps for long-running daemons or something  this
  becomes more of an issue, but for a typical web request the stat cache
  typically saves you dozens of system calls.

If you really insist on using clearstatcache(), the only thing (other than write caching) coming to my mind is, that you mave have a very huge upload folder, containing thousands of files.
Having many, many files in a single folder will definitely slow down re-stating.
If so, try to reduce the number of files to gain stat performance, e.g. by creating multiple folders, one folder for each initial char of your upload filenames, like upload/a/, upload/b/, etc.


text:
Q: User login with php/javascript I have a php script that I call through ajax to initialize session variables for a user login.  When I retrieve the session info later on it doesn't seem to be there.  What is missing from this.  I must say I am assuming that the $_SESSION variable is there.  I haven't done this before.
PHP code that searches for user in db and initializes session variable
while (true) {
    $md5_pw = md5($password_text);
    $r_getuser = mysql_query("SELECT * FROM users WHERE (user_name = BINARY '".mysql_real_escape_string($l_un_em)."' OR email = '".mysql_real_escape_string($l_un_em)."') AND (password = '$md5_pw' OR temp_password = '$md5_pw') AND status >= 0");
    if (mysql_num_rows($r_getuser) == 0) {
        /* echo $messages['log_un_em_pw_incorrect'];
        return; */
        $return['return_code'] = -1;
        $return['return_msg'] = $messages['log_un_em_pw_incorrect'];
        echo json_encode($return);
    }
    $row = mysql_fetch_assoc($r_getuser);
    /* if ($row['privs'] < 1) { echo $messages['log_no_privs']; break; } */
    if ($row['temp_password'] == $md5_pw) { //new password
        mysql_query("UPDATE users SET password = '".$md5_pw."', temp_password = NULL WHERE user_id = '{$row['user_id']}'");
    }
    $today = date('Y-m-d');
    if ($row['login_0'][0] == '9') { //first login
        mysql_query("UPDATE users SET login_0 = '".$today."', login_1 = '".$today."', login_cnt = 1 WHERE user_id = '{$row['user_id']}'");
    } else {
        mysql_query("UPDATE users SET login_1 = '".$today."', login_cnt = login_cnt+1 WHERE user_id = '{$row['user_id']}'");
    }
    $_SESSION['uid'] = $row['user_id'];
    $_SESSION['unm'] = stripslashes($row['user_name']);
    $_SESSION['uml'] = stripslashes($row['email']);
    $_SESSION['cL'] = $row['language'];
    /* echo '<meta http-equiv="refresh" content="0;url=livemass_CENTER34.php">'; */ //default page
    break;
}

PHP code to retrieve session variable.
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

echo 'user id '.$_SESSION['uid'].'
';
echo 'username '.$_SESSION['unm'].'
';
echo 'uml '.$_SESSION['uml'].'
';
echo 'cL '.$_SESSION['cL'].'
';

?>

Javascript to show session info.
$.ajax({
      url: "get_session_info.php",
      type: "GET",
      data: {},
      cache: false,
      async: false,
      success: function (response) {
      alert ('session info response
'+response);
      },
});

A: add session_start() to all your files which access session varibale values
<?php
session_start();
ini_set('display_errors', 1);

// remaining items

?>

http://php.net/manual/en/function.session-start.php

A: To build on what @Frits said. To use php sessions you must place the function session_start(); at the beginning of every page that you want to access $_SESSION on.


text:
Q: How to override Host header with Spring-boot-admin server I need to send a specific host value to the client app when the admin server hits the actuator endpoint. For example, I would like to be able to make the following curl request via admin server.

curl -H "Host: discovery-headless"  10.0.10.2:9080/actuator/metrics

I tried adding the following HttpHeadersProvider
 @Bean
 public HttpHeadersProvider customHttpHeadersProvider() {
    return (instance) -> {
     HttpHeaders httpHeaders = new HttpHeaders();
      String serviceName = instance.getRegistration().getName();
      String host = serviceName.contains("headless") ? serviceName : serviceName + "-headless";
      httpHeaders.add("Host", host);
      return httpHeaders;
    };
  }

and I can see that the header is present in the request but the endpoints being registered also have headless in their urls.

endpoints=Endpoints(endpoints={caches=Endpoint(id=caches, url=http://discovery-headless/actuator/caches),
loggers=Endpoint(id=loggers, url=http://discovery-headless/actuator/loggers),
logfile=Endpoint(id=logfile, url=http://discovery-headless/actuator/logfile),

I also tried adding a filter to webclient without using HttpHeadersProvider but I am seeing the same result. The endpoints all have the overwritten host in their urls.
@Override
  public void customize(Builder webClientBuilder) {
    webClientBuilder.filter(addHeadlessHeader());
  }

  private ExchangeFilterFunction addHeadlessHeader() {
    return (clientRequest, next) -> {
      Map<String, String> updatedHeaders = new HashMap<>();

      clientRequest.headers().forEach((key, values) -> {
        for (String value : values) {
          updatedHeaders.put(key, value);
        }
      });

      String hostHeader = updatedHeaders.get(HttpHeaders.HOST);

      if(hostHeader == null || (hostHeader != null && !hostHeader.contains("headless"))) {
        Instance service = (Instance) clientRequest.attribute("instance").get();

        if(service != null) {
          String serviceName = service.getRegistration().getName();
          hostHeader = serviceName + "-headless";
          updatedHeaders.put(HttpHeaders.HOST, hostHeader);
        }
      }

      ClientRequest updatedRequest = ClientRequest.from(clientRequest)
          .headers(headers -> headers.setAll(updatedHeaders))
          .build();
      return next.exchange(updatedRequest);
    };
  }

What is the correct way to override the Host header when making a request to a client instance?


text:
Q: Jquery Autocomplete: combobox + accent folding I am trying to mix the Jquery Ui Autocomplete combobox and accent folding examples, but it seems to be beyond my skills. I have tried to replace the mentions to 'text' by 'normalize(text)' in the combobox example but no cigar.
Combobox example: http://jqueryui.com/demos/autocomplete/#combobox
Accent Folding example: http://jqueryui.com/demos/autocomplete/#folding
Update:
I found the problem: the REGEX object was case-insensitive, but my normalize function wasn't.
Now I have a lesser problem: the code provides the well know text-highlight function as shown next:
if (this.value && (!request.term || matcher.test(normal) || matcher.test(text))) {
  return {
    label: text.replace(
    new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + $.ui.autocomplete.escapeRegex(request.term) + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>"),
    value: text,
    option: this
  };
}

Which is fine when the user types accented text, but can't highlight if the input is non-accented. Would there be a work around that, so that the text would be hightlit even when the user types without accents?
Thank you!

A: I found some solution:
if(this.value && ( !request.term || matcher.test(normalize(text)) || matcher.test(text)))


text:
Q: Antichains of maximum cardinality: posets vs lattices The following construction gives a poset such that no antichain has maximum cardinality: For $n\in\mathbb{N}\setminus\{0\}$, let "layer" $n$ consist of an antichain of $n$ points, and as for the ordering: if $m<n \in \mathbb{N}\setminus\{0\}$ every point of layer $m$ is smaller than every point in layer $n$.
This poset is far from being a lattice. Which leads to the
Question. Is there a lattice $(L,\leq)$ such that for every antichain $A\subseteq L$ there is an antichain $A' \subseteq L$ with $|A'|>|A|$?

A: Yes. For $n \in \mathbb{N}$ even let "layer" $n$ consist of a single point, and for $n \in \mathbb{N}$ odd let "layer" $n$ consist of $n$ points. The ordering is the same as yours, one point is less than another if and only if it lies in a lower layer.


text:
Q: Get all groups on n from array of length k I am looking for the best way to get all possible int arrays of length n from int array of length k, including an option for n-1 items to be null.
for example I have the array with 5 elements (k=5) and I want all combinations of 3 (n=3)
int[] numbers = new int[5] {1, 2, 3, 4, 5};

and the possible sub arrays of length 3:
{1,null,null},{1,null,2},{1,2,null}..... and so on.
What would be the best way to do it?
Matan

A: You could include null in your numbers array.
This code produces all possible permutations except of {null, null, null}.
var numbers = new int?[]{null, 1, 2, 3, 4, 5};
var result = new List<int?[]>();

foreach (int? x in numbers)
{
    foreach (int? y in numbers)
    {
        foreach (int? z in numbers)
        {
            if (x == null && y == null && z == null)
                continue;

            result.Add(new int?[] { x, y, z });
            Console.WriteLine("x: {0} - y: {1} - z: {2}", x, y, z);
        }
    }
}


text:
Q: Recursion with Clojure and Clojure for the Brave and True I'm trying to learn to program with the book Clojure for the Brave and True (CFTBAT). At the end of the crash course, the author makes us write a small programm to illustrate looping in Clojure. To explain the looping and recursing part of the program, here, the author writes a smaller example using loop and then shows it's possible to replace loop with a normal function definition.
It's this normal function definition example I can't understand. Here is the code:
(defn recursive-printer
    ([]
        (recursive-printer 0))
    ([iteration]
        (println iteration)
        (if (> iteration 3)
            (println "Bye!")
            (recursive-printer (inc iteration)))))

(recursive-printer)

I don't understand the code because I can't see where are the arguments of the function recursive-printer. In Clojure, the arguments of a function are supposed to be in brackets and the body in parenthesis. So, in this example, the arguments would be an empty argument [] and iteration. But then why are they put between parenthesis too?
And what is (recursive-printer 0) Is it a function call, where the function calls itself?
If someone could explain me how this piece of code works, that would be much appreciated.

A: In clojure you can define a function such that it can take different numbers of
arguments e.g.
(defn foo []
  ....)

is a function which takes no arguments. It is called like this ..
(foo)

(defn foo [x]
  ...)

is a function which takes 1 argument. It can be called like
(foo :a)

but sometimes, you may want to define a function which takes zero or 1
argument. To do this, you use a slightly different format
(defn foo
  ([] ;no argument form
    ...)
  ([x] ;single argument form
    ...))

A common idiom is to use a zero argument form in a recursive function definition
and include a single 'accumulator' argument form as the main part of the
function. So, looking at your example, you have
(defn recursive-printer
    ([] ; zero argument form
        (recursive-printer 0))
    ([iteration] ; 1 argument form
        (println iteration)
        (if (> iteration 3)
            (println "Bye!")
            (recursive-printer (inc iteration)))))

(recursive-printer)

When you call (recursive-printer) it calls the first form (zero argument
form). That form in turn calls the function with a single argument of 0. This
calls the second form.
The second form first prints out the argument, then tests to see if it is
greater than 3, which in the first call it is not as it is 0, so it executes the
'else' statement, which does a recursive call with a new argument which is the
current argument increased by 1. Now your argument is 1 and it is printed
out. the test is still false as 1 is not > 3, so the function is called again
with the argument increased by 1 i.e. 2. In this call, 2 is printed, the test is
still not grater than three, so the function is called again with the argument
increased to 3. In this call, 3 is printed and the test is still not > 3, so the
argument is incremented to 4 and the function called again with 4 as the
argument. The value 4 is printed, but this time 4 is > 3, so the string "Bye" is
printed and as this is the terminating condition, no further recursive call is
made and the stack unwinds and the function terminates.

A: We can drop the zero arity:
(defn recursive-printer [iteration]
  (println iteration)
  (if (> iteration 3)
    (println "Bye!")
    (recursive-printer (inc iteration))))

... and call the function with an explicit 0 argument:
(recursive-printer 0)
0
1
2
3
4
Bye!
=> nil

This lets us concentrate on the recursion. Since the recursive call is the last thing done (in tail position), we can use recur instead:
(defn recursive-printer [iteration]
  (println iteration)
  (if (> iteration 3)
    (println "Bye!")
    (recur (inc iteration))))

... with exactly the same effect.
The extra arity just confuses things, I think.


text:
Q: MySql multiple results tables for each unique values Sorry if the title is not well explained tried my best.
I currently have this transactions table which hold the records, every row has an agent and a currency assigned to it.

id
amount
agent
currency_id

1
400.00
agent1
1

2
170.00
agent5
3

3
110.00
agent4
2

4
430.00
agent5
3

5
155.00
agent1
1

6
370.00
agent2
2

7
10.00
agent2
2

8
150.00
agent1
1

9
130.00
agent3
3

10
445.00
agent4
2

And this other table called currency which holds the unique currency and name.

id
currency

1
USD

2
VES

3
EUR

The query that I want to make is a SUM and group by agent for every currency there is. I am able to do it with a single query like this but only for one currency in the WHERE clause:
SELECT a.agent,
       SUM(a.amount)
FROM transactions AS a
INNER JOIN currency AS b ON b.id = a.currency_id
WHERE b.currency = 'VES'
GROUP BY a.agent

I will be getting this result which is only for the VES currency

agent
total

agent2
380.00

agent4
555.00

I am looking for one query that allow me to get the result of all 3 current existing currencies (USD, VES, EUR) this should give a result of 3 different tables

A: I suspect that you want a report showing all agents, currencies, and their sums.  You may try using this cross join approach:
SELECT a.agent, c.currency, COALESCE(SUM(t.amount), 0) AS total
FROM (SELECT DISTINCT agent FROM transactions) a
CROSS JOIN currency c
LEFT JOIN transactions t
    ON t.agent = a.agent AND
       t.currency_id = c.id
GROUP BY 1, 2
ORDER BY 1, 2;

The first two tables in the join generate all combinations of agents and currencies.  We join this to your transactions table and aggregate to get the totals.


text:
Q: How to call vim script in C language what's my goal:
i want a program to get session.vim and viminfo.info file for each file being edited by vim,
and scp these file to another pc, then i can continue the work on another pc.
problems:

*

*maybe the file isn't saved.

*

*should save the file before the program generate the session.vim.

*how get the absolute path of the file.

*

*i just can get the file name using ps -ef | grep vim.

*getcwd() can get the current working derectory.but, i can't push it to my program written by C.

Here is my solution, but it doesn't work, maybe you get a better solution, i need your help.
kill all vim process, and get session.vim and viminfo.info for each file.
in my C code:
system(kill -9 pid);//pid is the pid of vim process.

in my .vimrc file:
autocmd VimEnter * let s:this_session='.'.expand('%:t').'.vim'
autocmd VimLeave * if v:dying | call Somefunc() | endif
function! Somefunc()
    silent! wa
    execute 'mksession! '.fnameescape(s:this_session)
endfunction

it does not work.
do i make myself clear? i'm not good at english.
i'd be very grateful for any help.

A: man kill says this:

SIGKILL      9    kill (cannot be caught or ignored)

With the -9 argument, Vim (as well as any other process) has no chance to react to the signal; the process will be forcibly terminated. Try sending the default SIGTERM (15) by omitting the -9 argument. See here for more information.


text:
Q: r Evaluate condition by group in data.table to filter rows, data structure: list of data.tables Another quick data.table question related to a list of data.tables:
foo <- rep(1:3, times=3)
lorem <- c(20, 30, -10, 405, 70, 20, 35, 50, 30)
df1 <- data.table(foo, lorem)

foo1 <- rep(1:3, times=3)
lorem1 <- c(0, 30, -50, 500, 20, 10, 500, 20, 10)
df2 <- data.table(foo1, lorem1)
setnames(df2, 1:2,c("foo", "lorem"))

df.list <- list(df1, df2)
print(df.list)

[[1]]
   foo lorem
1:   1    20
2:   2    30
3:   3   -10
4:   1   405
5:   2    70
6:   3    20
7:   1    35
8:   2    50
9:   3    30

[[2]]
   foo lorem
1:   1     0
2:   2    30
3:   3   -50
4:   1   500
5:   2    20
6:   3    10
7:   1   500
8:   2    20
9:   3    10

I am trying to drop all observations where variations within the lorem column exceed 20x or are negative.
So for instance, for foo == 1 (my id column), his variation would be larger than 20, since of the values (20, 405, 35), (max = 405 / min = 20) > 20.
This is complicated by the fact that I have to run this on a list of 40 data.tables.
I tried to run the following:
> tester <- purrr::map(df.list, function(dat) {
    + dat[dat[, .I[which.max(lorem) / which.min(lorem) < 20], by=foo]$V1]
    + })
    >
    > print(tester)
    [[1]]
       foo lorem
    1:   1    20
    2:   1   405
    3:   1    35
    4:   2    30
    5:   2    70
    6:   2    50
    7:   3   -10
    8:   3    20
    9:   3    30

    [[2]]
       foo lorem
    1:   1     0
    2:   1   500
    3:   1   500
    4:   2    30
    5:   2    20
    6:   2    20
    7:   3   -50
    8:   3    10
    9:   3    10

But as you can see this only sorted the list by id. Not too familiar with the .I / .SD subsetting that data.table uses. How could I approach this problem to get the following output:
[[1]]
       foo lorem
       2    30
       2    70
       2    50

[[2]]
       foo lorem
       2    30
       2    20
       2    20

So I keep only those rows where max(lorem) / min(lorem) < 20 or are non-negative?

A: After looping over the list with lapply, create logical expression with max and min and check if all the values are non-negative, grouped by 'foo', then extract the row index (.I) to subset the rows of the dataset
lapply(df.list, function(dat) dat[dat[,
   .I[all(sign(lorem) >=0) &&(max(lorem) <= 20 * min(lorem))], foo]$V1])
#[[1]]
#   foo lorem
#1:   2    30
#2:   2    70
#3:   2    50

#[[2]]
#   foo lorem
#1:   2    30
#2:   2    20
#3:   2    20

If we are using map from purrr
library(purrr)
map(df.list, ~ .x[.x[, .I[all(sign(lorem) >= 0) &&
          (max(lorem) <= 20 * min(lorem))], foo]$V1])


text:
Q: What Envoy metric should be used to measure server latency? My server is a service deployed to service mesh implemented by Envoy and Istio sidecars. I only have access to Envoy metrics. The HTTP server receives requests from clients external to the mesh as in the diagram below:

I want to measure the average latency it takes for the server to respond to the external client and I'm having trouble understanding whether I need upstream or downstream metrics and then whether external/internal metrics are needed. According to Envoy docs:

Downstream: A downstream host connects to Envoy, sends requests, and receives responses.

Upstream: An upstream host receives connections and requests from Envoy and returns responses.

In this scenario as far as I understand:

*

*Ingress Gateway acts as upstream for the external client and downstream for the Envoy sidecar.

*Envoy sidecar acts as upstream for Ingress Gateway and downstream for HTTP server.

As far as I understand both Ingress Gateway and Envoy sidecar publish downstream and upstream metrics. How do I get the total latency: from the point a request reached Ingress Gateway to the point Ingress Gateway returned last byte of the response?

A: There doesn't seem to be a noticeable difference between the two, plus if you want to configure per route metrics you can achieve something like that using virtual clusters but it will only give you upstream metrics.
From https://github.com/envoyproxy/envoy/issues/10967

Assuming there are no blocking filters in use (e.g. ext_auth) I expect the times to be reasonably close together.

About per route metrics see https://github.com/envoyproxy/envoy/issues/23642


text:
Q: Clean Monocrome image with Imagemagik in iOS I'm trying to create a code that allows me to clear images to be read by and OCR engine. So far I haven't been able to accomplish much. Only install Imagemagink on my iOS project and use some of the API functions to create a Gray Scale image.
What I'm trying to achieve is something like this:
convert \( $infile -colorspace gray -type grayscale -contrast-stretch 0 \) \ \( -clone 0 -colorspace gray -negate -lat ${filtersize}x${filtersize}+${offset}% -contrast-stretch 0 \) \ -compose copy_opacity -composite -fill "$bgcolor" -opaque none +matte \ -deskew 40% -sharpen 0x1 \ $outfile

Now the problem is that I haven't been able to replicate that on My Code. So my questions are:

*

*Does any one knows a way of using the "ConvertImageCommand()" method using an UIImage as input instead of a file path? (Example here: http://www.imagemagick.org/discourse-server/viewtopic.php?t=25704)

*As an alternative and keep on going with my actual code, could anyone point me in the right direction of converting the above command into an API method to complete the code below?
So far I've found that the "-lat" option equivalent in the API is: "MagickAdaptiveThresholdImage()"
regards,
-(UIImage *)drawMonochromeImage:(UIImage *)image
{
    // Create temporary file
    NSString *tempFilePath = [NSTemporaryDirectory()
                              stringByAppendingPathComponent:@"temp.jpg"];

    MagickWandGenesis();
    MagickWand *wand = NewMagickWand();
    NSData *data = UIImagePNGRepresentation(image);
    MagickReadImageBlob(wand, [data bytes], [data length]);

    // Monochrome image
    //MagickQuantizeImage(wand,2,GRAYColorspace,1,MagickFalse,MagickFalse);

    MagickDespeckleImage(wand);
    MagickEnhanceImage(wand);

    MagickQuantizeImage(wand,256,GRAYColorspace,0,MagickFalse,MagickFalse);
    MagickBrightnessContrastImage(wand,-40,30);

    // Write to temporary file
    MagickWriteImage(wand,
                     [tempFilePath cStringUsingEncoding:NSASCIIStringEncoding]
                     );

    // Load UIImage from temporary file
    UIImage *imgObj = [UIImage imageWithContentsOfFile:tempFilePath];

    // Display on device
    return imgObj;
   // [self.imageView setContentMode:UIViewContentModeScaleAspectFit];
}

A: Finally I was able to use the "ConvertImageCommand()" function of the ImageMagick API for C and then used this code to generate the image with grate results!.
char *argv[] = {"convert","-respect-parenthesis","\(", input, "-set", "-colorspace", "RGB", "-colorspace", "gray", "-type", "grayscale","-colorspace","RGB", "-normalize","\)","\(","-clone", "0","-set","-colorspace", "RGB","-colorspace","gray","-negate", "-lat", "15x15+5%", "-contrast-stretch", "0","\)","-compose","copy_opacity","-composite","-fill","white","-opaque","none","+matte", output, NULL};

I hope this can be useful to someone.
Regards,


text:
Q: Code won't run when loaded Can anyone see where I have messed up please ?
the output I am looking to achive is to have a box 78 pixels x 78 pixels and for each pixel have a link to another page, at the moment only the 1st pixel works.
The code loads on the page and can been seen under the image, how is this happings ?

<title>Untitled Page</title>

<map name="ImageMap1_map">
foreach ($string){
    $x = 1; $y = 1; $z = 1;$output = '';
    for($x=1;$x<79;$x++)
    {
    for($y=1;$y<79;$y++)
    $string = $x .','.$y.','.$z;
    $output .= '<area shape="circle" coords="'. $string . '" href="./index.html" target="_blank" alt="" yellow="">'
    }
    }
    echo $output;

</map>

A: You need to wrap your code in the php tags
<?php
foreach ($string){
    $x = 1; $y = 1; $z = 1;$output = '';
    for($x=1;$x<79;$x++)
    {
    for($y=1;$y<79;$y++)
    $string = $x .','.$y.','.$z;
    $output .= '<area shape="circle" coords="'. $string . '" href="./index.html" target="_blank" alt="" yellow="">'
    }
    }
    echo $output;
?>

A: You added Code as just plain text, let it get executed by php, add php tags.
If php tags are present, then only server knows to execute it and process, else it is considered plain text.
So use like this:
foreach ($string){
$x = 1; $y = 1; $z = 1;$output = '';
for($x=1;$x<79;$x++)
{
for($y=1;$y<79;$y++)
$string = $x .','.$y.','.$z;
$output .= '<area shape="circle" coords="'. $string . '" href="./index.html" target="_blank" alt="" yellow="">'
}
}
echo $output;


text:
Q: Proper syntax to generate "text" images with ImageMagick I'm am trying to generate test images with ImageMagick. The image needs to only contain text. Bluntly using the example on the IM site doesn't work:
convert -background lightblue -fill blue -font Roboto -pointsize 72 label:Anthony label.gif

Yields:
convert.im6: unable to read font `Roboto' @ warning/annotate.c/RenderType/853.
convert.im6: no images defined `label.gif' @ error/convert.c/ConvertImageCommand/3044.

So 1) what is required to be able to use font names (my whole desktop uses Roboto, so I assume it is properly installed, and other fonts names don't work either) and 2) if I remove the font spec I still get the second line and no output.
Am I missing something?
Using ImageMagick 6.7.7-10 2016-11-29 Q16 on Ubuntu 14.04.

A: It's a bug in the particular version of ImageMagick you are using, resulting from a incorrect backport of a bugfix patch.
The problematic patch is Debian patch 0161-Do-not-ignore-SetImageBias-bias-value. I can't tell if that was included in the 14-November-2016 security update to 8:6.7.7.10-6ubuntu3.2 or the 29-November-2016 security patch to 8:6.7.7.10-6ubuntu3.3 (or, at least, I didn't bother trying to figure it out, since it's not that important.) The patch was created as a backport of this security patch, but because of a reorganization of the logic in the file coders/label.c, the correction ended up being inserted in the wrong place.
In essence, the logic of label.c is as follows:

*

*if the image's size or pointsize is not specified, work out the best fit

*if the image's width was not specified, copy it from the computed width

*if the image's height was not specified, copy it from the computed height

*if the image's pointsize was not specified, copy it from the computed pointsize

*make some other relevant settings to image parameters

*Render the text into the image.

The security patch was intended to avoid step 6 if the resulting image size could not be used. This avoids a possible Denial of Service attack when ImageMagick is being used on a web back-end (which is common). It adds:
3a. If the image dimensions are unusable, immediately fail.
Unfortunately, in the version to which to patch is applied, the above steps were in a different order, with the third step being intermingled with step 5. (This made no real difference, as far as I can see, but it was a bit disorganized, which is probably why it was subsequently fixed.) The result is that the added step 3a is inserted before the image's height has been copied from the computed height. This causes the check to fail if the image did not originally have a height, even though a correct height had been computed at that point.
The instructions clearly indicate that a label: source does not require a -size (or -pointsize) parameter. But with the misplaced patch, this turns out to be incorrect; unless a height is specified in the geometry, the label will not be generated.
I haven't generated a bug report for this because it only applies to an outdated version of ImageMagic on an outdated version of Ubuntu (and possibly of Debian). It happens that I and OP are both using this outdated version of Ubuntu on some machine, and my recommendation to both of us is to upgrade. But in case anyone else has this problem, I'm answering the question (which I found when trying to research the identical problem on my machine.)

A: Eventually got it to work using -size instead of -pointsize, and switched to caption since I can better control the position:
convert -background transparent -fill darkblue -font Roboto-Regular -size 200x100 -gravity center 'caption:Test' out.png

A: convert -background lightblue -fill blue -font Arial -pointsize 72 label:"Anthony" label.gif

The above works fine for me on IM 6.9.7.0 Q16 Mac OSX

A: Worked OK for me on a windows setup version 7 apart from the font error as I do not have that font installed. Setting it to arial removed the font error.
Try this to see if Imagemagick can see your font:
identify -list type

Otherwise I would try linking directly to your font with the path and putting the .ttf on the end. I assume your font is a .ttf one as Imagemagick supports that type and one other that I can not remember.
Out of interest your version is 4.5 years old.


text:
Q: Performing exact match when comparing variables in SPSS Statistics I'm wondering if there's a way for me to perform an exact match compare in SPSS. Currently, using the following will return system missing (null) in cases where one variable is sysmis:
compute var1_comparison = * Some logic here.
compute var1_check = var1 = var1_comparison.

The results look like this (hypens representing null values):
ID   var1    var1_comparison    var1_check
 1      3                  3             1
 2      4                  3             0
 3      -                  2             -
 4      1                  1             1
 5      -                  -             -

What I want is this:
ID   var1    var1_comparison    var1_check
 1      3                  3             1
 2      4                  3             0
 3      -                  2             0
 4      1                  1             1
 5      -                  -             1

Is this possible using just plain SPSS syntax? I'm also open to using the Python extension, though I'm not as familiar with it.

A: Here's a slightly different approach, using temporary scratch variables (prefixed by a hash (#)):
recode var1 var1_comparison (sysmis=-99) (else=copy) into #v1 #v2.
compute Check=(#v1 = #v2).

A: This is to recreate your example:
data list list/ID var1 var1_comparison.
begin data
 1, 3,  3
 2 , 4, 3
 3, , 2
 4, 1, 1
 5, ,
end data.

Now you have to deal separately with the situation where both values are missing, and then complete the calculation in all other situations:
do if missing(var1) or missing(var1_comparison).
compute var1_check=(missing(var1) and missing(var1_comparison)).
else.
compute var1_check = (var1 = var1_comparison).
end if.


text:
Q: Community ♦ seems to be bumping new questions more frequently than usual On Chemistry.SE:

These are all Community ♦ bumps, separated by exactly one hour (They occur on hour:38:16 UTC). Could the bot be sedated please? We're a 4-questions-per-day site; a bump an hour is not good for business.
We used to have one bump per day. This is evident if you scroll down on the homepage and check the timestamps (screenshot).
Apparently the number of questions bumped per hour is a configuration value. Maybe this got tweaked?

A: No change to the configuration value so far as I can see - it's max 1 per hour (which is what you're observing).
Note that the posts eligible for bumping are those scoring >= 0 that have gone at least 30 days with no activity, have at least one non-deleted answer scoring 0 and none scoring more than that, and no accepted answer (also, they can't be deleted or closed).
There's a pretty reasonable chance that you just didn't have very many questions meeting those criteria until today...


text:
Q: MongoParseError: URI does not have hostname, domain name and tld I'm getting this error when I try to connect my app(nodejs) to mongodb. I really appreciate your help here.
MongoParseError: URI does not have hostname, domain name and tld
    at parseSrvConnectionString (E:\Projects\NodeAPI\node_modules\mongodb-core\lib\uri_parser.js:41:21)
    at parseConnectionString (E:\Projects\NodeAPI\node_modules\mongodb-core\lib\uri_parser.js:509:12)
    at connect (E:\Projects\NodeAPI\node_modules\mongodb\lib\operations\mongo_client_ops.js:195:3)
    at connectOp (E:\Projects\NodeAPI\node_modules\mongodb\lib\operations\mongo_client_ops.js:284:3)
    at executeOperation (E:\Projects\NodeAPI\node_modules\mongodb\lib\utils.js:416:24)
    at MongoClient.connect (E:\Projects\NodeAPI\node_modules\mongodb\lib\mongo_client.js:175:10)
    at Function.MongoClient.connect (E:\Projects\NodeAPI\node_modules\mongodb\lib\mongo_client.js:341:22)
    at Object.<anonymous> (E:\Projects\NodeAPI\server.js:12:13)
    at Module._compile (internal/modules/cjs/loader.js:816:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:827:10)
  name: 'MongoParseError',
  [Symbol(mongoErrorContextSymbol)]: {} }

My code:
db.js
 module.exports = {
uri : "mongodb+srv://mithun:*******@cluster0-s089x.mongodb.net/test?retryWrites=true"}

==================================================================
node_route.js
 module.exports = function(app, db){
app.post('/notes', (req, res) => {
    const note = {text: req.body.body, title: req.body.title};
    db.collection('notes').insert(note, (err, results) => {
        if(err){
            res.send({'error': 'An error has occured'});
        } else {
            res.send(result.ops[0]);
        }
    });
 });
 };

=======================================================================
index.js
 const noteRoutes = require('./note_route');
 module.exports = function(app, db){
 noteRoutes(app, db);
}

=========================================================================
server.js
       const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const bodyParser = require('body-parser');
const db = require('./config/db');
const app = express();
const port = 8000;
 app.use(bodyParser.urlencoded({extended: true}));
  MongoClient.connect(db.uri,{ useNewUrlParser: true }, (err, database) =>
  {
     if (err) return console.log(err);
     require('./app/routes')(app, database);
      app.listen(port, () => {
           console.log("We are live on " +port);
  });
 });

===========================================================================
module.exports = {
uri : "mongodb+srv://mithun:m3Thun#47@cluster0-s089x.mongodb.net/test?retryWrites=true&ssl=false"

}
I've tried with ssl= false but the error remains same.

A: Convert the special characters (: / ? # [ ] @) in your password or username to percentange characters i.e

*

*@ = %40

*' = %27

*! = %21

*...
e.g.  p@ssw0rd'9'! becomes p%40ssw0rd%279%27%21

A: Solution-1: If you are using any special character in your password you need to encode the particular character as %+ASCII_code_of_the_character below link explains everything.
https://docs.atlas.mongodb.com/troubleshoot-connection/#special-characters-in-connection-string-password
Solution-2:
Click on auto-generate password and paste it into the connection string, it will work.

A:
Use of the +srv connection string modifier automatically sets the ssl
  option to true for the connection. You can override this behavior by
  explicitly setting the ssl option to false with ssl=false in the query
  string.

May it can be a ssl problem? Try with no ssl:  ssl=false

A: I also faced this problem.
In my case, I was using npm dotenv package to get the username the password from a .env file.
When I logged the values from the .env file, I noticed it was not retrieving the password correctly.
It could be an issue with either the username or password.

A: try to encode your password

*

*here :encode your pass

*ref: Special characters in connection string password
ex)
# before encode
test@#123%^
# after encode
test%40%23123%25%5E

this work for me :)

A: This error occurs because if you use some of the special characters in your passwords
like: / ? # [ ] @

*

*Now you have to convert your password to a percentage encoding password so for that put,

@ = %40 (put %40 instead of @)
? = %3F

# = %23

[ = %5B

] = %5D if some special character doesn't find here use below link.

*Just put your password and get the percentage encoded password: https://www.w3schools.com/tags/ref_urlencode.ASP

A:
If the username or password includes the following characters:

: **/ ? # [ ] @**

those characters must be converted using
percent encoding
You can convert using this site-

https://www.w3schools.com/tags/ref_urlencode.ASP

I saw your MONGO_URI password contains # symbole which need to encode to %23
module.exports = {
uri : "mongodb+srv://mithun:m3Thun%2347@cluster0-s089x.mongodb.net/test?retryWrites=true&ssl=false"
}

A: Make sure that the username password is character encoded if you have special characters in it like @!: etc or used MongoDB password generator
See:
 https://docs.mongodb.com/manual/reference/connection-string/#examples

A: This issue comes if your MongoDB User contains any special characters
Try removing any special character from the password

A: In my case, it turns out I had a space in the connection string, which was hard to see in the small text input field that Heroku provides for config parameters.

A: Even I faced the same issue and I did these steps it got worked for me!

*

*Goto your monogoDB database (website).

*Change the user password to automatically generated password.

*Paste that auto generated password in the URI string.

*Check the URI once and twice and confirm it and run the app in shell.

A: I think your password may contain & or ? (or may special characters) so u should remove it, cause parsing error

A: You might have special characters in your password string.
E.g. If your password was - password!#, !# are special characters, they would have to be rewritten as %23%21. Thus, your connection string password should be password%23%21.
For more information - MongoDB, ASCII

A: Ensure special characters in your password are encoded. For example if your password contains '#' you should replace the literal '#' character with '%23' where 23 is the hex code for '#' see: https://docs.atlas.mongodb.com/troubleshoot-connection/#special-characters-in-connection-string-password

A: use '%23' instead of # in your password
and
mongoURI =  "mongodb+srv://username:password@devconnector.jpokp.mongodb.net/dbname?retryWrites=true&w=majority"
mongoose .connect(mongoURI, { useNewUrlParser: true }) .then(() => console.log("MongoDB connected")) .catch((err) => console.log(err));

A: I Resolved it by these steps in MongoDB Compass:-

*

*Click On "Fill in connection fields individually"

*fill your Username and password

Click on Connect

A: mongodb+srv://username:password@cluster0.qjasz.mongodb.net/database-name

use username and password without <>

A: remove <> from username and password
and password special character is encoded using the website given below
https://www.url-encode-decode.com/
example :
@123Password# encoded to %40123Password%23

A:
I was getting below error while database connection(MongoDB) in my node application:

Error: URI must include hostname, domain name, and tld
I found the documentation for special-characters-in-connection-string-password from official site of MongoDB: Click  Here!
As If your password includes special characters, and you are using your password in a connection string URI, encode the special characters.
databaseURI = 'mongodb+srv://<USERNAME>:<PASSWORD>@cluster0.jekotsl.mongodb.net/?retryWrites=true&w=majority'

Root Cause for the reported error: I was entering plain password instead of encoding the special characters.
Solution: I encoded the password from Encode to URL-encoded format , then DB connection was succeeded.

A: Prior to version 3, the library expected properties to be prefixed with env.. The default behaviour going forward is to not use a prefix. If you require a prefix, then you can provide one like this:
prefix=env.


text:
Q: put a pipe in a dictionary PMU_PIPE_MAP = {}

PIPE= 'tmp/%s.pipe' % hostname
if not os.path.exists(PIPE):
    os.mkfifo(PIPE)

PMU_PIPE_MAP[hostname] = os.open(PIPE, os.O_WRONLY)

Im trying to open n pipes. In order to keep track of them I'd like to store them somehow - like in a dictionary - I thought that the above code should work but it freezes during execution. Any suggestions?
This does work however:
pipein = os.open(PIPE, os.O_WRONLY)

A: Aha! apparently there has to be a read on the other end before we can get a return from the pipe. So the question that I asked was not correct because I failed to test the two scenarios in the same way. So my problem was in understanding how pipes work. In this situation the dictionary entry will succeed once the piping is opened on the 'read' end but will block until then.
how to determine if pipe can be written

A: It is not tested, but may it will help you
import os, tempfile

tmpdir = tempfile.mkdtemp()

PMU_FIFO_MAP = {}

def openFIFO(pname):
    filename = os.path.join(tmpdir, '%s' % pname)
    fifo = None
    try:
        os.mkfifo(filename)
        fifo = os.open(PIPE, os.O_WRONLY)
    except OSError, e:
        print "Failed to create FIFO: %s" % e
        print e.printStackTrace()
    return fifo

def closeFIFO(fname, fifo):
    fifo.close()
    os.remove(fname)

for hostname in hostnames:
    fifo = openFIFO(hostname)
    if fifo:
        PMU_FIFO_MAP[hostname] = fifo

# do stuff with fifos

for fname, fifo in PMU_FIFO_MAP.items():
    closeFIFO(fname, fifo)
    del PMU_FIFO_MAP[hostname]

os.rmdir(tmpdir)

Also see possible Create a temporary FIFO (named pipe) in Python?.


text:
Q: PostgreSQL: query records where ALL joined record attributes match where clause I found a similar question but it didn't satisfy my answer: SQL: Select records where ALL joined records satisfy some condition
I have two tables, orders and shipments
orders have_many shipments
shipments have attribute status open/closed
I would like to query orders, where all of its shipments are closed:
Assuming table of:

*

*order1, 2 shipments: 1open, 1closed

*order2, 3 shipments: 1open, 2closed

*order3, 1 shipments: 0open, 1closed

*order4, 2 shipments: 0open, 2closed

Running the query returns records for order3 and order4
I am currently doing this with N+1 using application code, I'd like to just implement in SQL.

A: Let's look for all orders for which there does not exist any shipment (matching that order) with a status other than closed.
Order.where("NOT EXISTS(SELECT 1 FROM shipments WHERE shipments.order_id = orders.id AND status != 'closed')"

A: demo:db<>fiddle
Aggregate the status and then you can filter with the ALL operator which checks if all array elements fit the condition.
SELECT order_id
FROM (
    SELECT order_id, array_agg(status) status
    FROM shipments
    GROUP BY order_id
) s
WHERE 'closed' = ALL(status)