text:
Q: How to Display and load images from URL that are visible in UITableViewCell I tried this link, but I didn't get my solution.
I want to display and load images from URL that are visible in UITableViewCell and other cell images have to load when we scroll table view in Objective-C.

A: use SDWebImage for this. it has almost all features what you need. It's also easy to coding like this.
Objective C
[imageView sd_setImageWithURL:[NSURL URLWithString:@"your domain"]
             placeholderImage:[UIImage imageNamed:@"placeholder.png"]];

Additional:
swift 3:
imageView.sd_setImage(with: URL(string: "your domain"), placeholderImage: UIImage(named: "placeholder.png"))

A: Rajashekar simply you can do this
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *strCell=@"cell";
    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:strCell];
    if (cell==nil) {
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:strCell];
    }
    NSString *strImgURL = @"YourImageURL";
    NSError* error = nil;
    NSURL *fileURL = [NSURL fileURLWithPath:strImgURL];
    NSData* data = [NSData dataWithContentsOfURL:fileURL options:NSDataReadingUncached error:&error];
    if (error) {
        NSLog(@"%@", [error localizedDescription]);
    } else {
        NSLog(@"Data has loaded successfully.");
    }
    UIImage *img = [[UIImage alloc] initWithData:data];
    cell.imageView.image = img;

    return cell;
}


text:
Q: Find the files with same md5sum and print ones alike in the same line I'm trying to do one written in the title, I explain with one example:
Tree directory:
(A B C D H F G are my file)
dir0/
dir0/A    //MD5sum equal MD5sum B
dir0/C
dir0/D   // MD5sum equal MD5sum F G
dir0/dir1/B  // MD5sum equal MD5sum A
dir0/dir1/H
dir0/dir1/dir2/G  //MD5sum equal MD5sum F D
dir0/dir1/dir2/F  //MD5sum equal MD5sum G D

with this command:
find dir0/ -type f -print0 | xargs -0 md5sum | sort | uniq -w32 --all-repeated=prepend | awk '{ print $2 }'

I search all file in a dir0 and subdir, calculating the MD5sum, sort , select only files equals and divided into groups, print only path files.
Ok this works and I have this output:
dir0/A        ]
dir0/dir1/B   ] first group

dir0/D             ]
dir0/dir1/dir2/F   ]
dir0/dir1/dir2/G   ] second group

how can I have an output in the following way?(each file with the same MD5sum in the same line, obviously without " first, second ... group")
dir0/A dir0/dir1/B  ] first group
dir0/D dir0/dir1/dir2/F dir0/dir1/dir2/G ] second group

A: The shortest way to do this would be to add a pipeline step like this:
awk 'BEGIN{RS=RS RS}{$1=$1}1'

RS = RS RS causes Awk to use "\n\n" as its record separator, thus reading each block as a single record. The FS field separator is whitespace, which includes newlines, so we don't have to do any work to split the lines.
$1 = $1 doesn't really change the value of $1, but Awk thinks it could have, which means it'll reconstruct $0 (which currently has newlines in it) from $1, $2, etc., joining with OFS (which is " " by default).
1 causes Awk to print $0 (and ORS, which is still a single newline) on every record.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Django models timestamp in MYSQL Db I want to store time as unix timestamp in my MYSQL database, I have django project with model:
date = models.DateField()

But I didn't find any models.Timestamp()
or anything similiar. Is there a way to create timestamp column for MYSQL Db in Django? I found some articles here on stack but they are 5+ years old so there might a be a better solution now.

A: In Django, one usually uses a DateTimeField [Django-doc] for that. It is a column that thus stores a combination of date and time.
One can let Django automatically intialize (or update) the timestamp if the record is constructed or updated with auto_now_add=True [Django-doc] to initialize it when the record was created, and auto_now=True [Django-doc] to update. So it is a common pattern to see a (base)model like:
class TimestampModel(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

    class Meta:
        abstract = True
such that subclasses of the TimestampModel thus have two extra columns created and updated that store the time when the object was created and last updated respectively.
A datetime column has a larger range, as is specified in the MySQL documentation:

The DATETIME type is used for values that contain both date and time
  parts. MySQL retrieves and displays DATETIME values in 'YYYY-MM-DD hh:mm:ss' format. The supported range is '1000-01-01 00:00:00' to
  '9999-12-31 23:59:59'.
The TIMESTAMP data type is used for values that contain both date
  and time parts. TIMESTAMP has a range of '1970-01-01 00:00:01' UTC to '2038-01-19 03:14:07' UTC.


text:
Q: What is the default mongod write concern in which version? I could not find in mongodb's documentation what's the default write concern and how an "acknowledged write" is defined.
It seems that this have changed throughout the different mongodb versions as shows the v3.2 documentation for example:

In 3.2-versions earlier than 3.2.6, w: "majority" implies j: true if journaling is enabled. With earlier versions of MongoDB, w: majority" does not imply journaling.

Or:

Changed in version 3.0: Prior to MongoDB 3.0, w: "majority" refers to the majority of the replica set's members.

Or:

Changed in version 2.6: In Master/Slave deployments, MongoDB treats w: "majority" as equivalent to w: 1. In earlier versions of MongoDB, w: "majority" produces an error in master/slave deployments.

Also, I'm wondering that "majority" refers to all voting nodes in v3.2 documentation :

Requests acknowledgment that write operations have propagated to the majority of voting nodes [1], including the primary.

Does this mean that even arbiters count since they are voting nodes? So, for example, if I have a replSet consisting of 2 data bearing nodes plus 1 arbiter, a write operation with write concern "majority" would succeed even if 1 data bearing node went down because the write was acknowledged by the remaining data bearing node and the arbiter, hence the majority?

A: The default write concern in MongoDB has been w:1 from as far back as MongoDB 2.2 in 2012.
EDIT: Since MongoDB 5.0, the default write concern is majority except in some cases where arbiters are involved.
There are three different settings you can use to setup write concern in current MongoDB versions (version 3.2.6 and newer):

*

*w setting: how many nodes should acknowledge the write before declaring it a success. Default is 1, meaning the primary node's acknowledgement is sufficient.

*j setting: do the writes must be journaled before acknowledged? Default depends on writeConcernMajorityJournalDefault.

*writeConcernMajorityJournalDefault: if you specify w:majority write concern setting for your writes without setting j, what is the implied j value? Default is true (writes should be journaled in the majority of the voting nodes before it is acknowledged).

There is also a wtimeout setting to configure how long MongoDB should wait for write concern to be satisfied before informing the client that the write has not been acknowledged. Otherwise, writes waiting for write concern to be satisfied can wait forever instead of failing.
The special setting here is w:majority. This means that writes must propagate to the majority of voting nodes (and also to their journals) in a replica set to be acknowledged. This is arguably the safest setting while providing good performance, because:

*

*It prevents acknowledged writes to be rolled back in the event of failures.

*It regulates the application's throughput so that it won't send writes faster than what the replica set can handle (due to hardware constraints, network situation, etc.).

As you have imagined, voting nodes does include the arbiter. Thus, in a replica set with primary-secondary-arbiter setup, w:majority could fail in a scenario where:

*

*One of the data-bearing node is offline for some reason.

*The replica set is still online with a writable primary, since the topology is now primary-arbiter-offline.

*Writes with w:1 will succeed as usual, but those writes could be rolled back (since it was not written to the majority of voting-data-bearing nodes).

*Since the arbiter carries no data, w:majority writes will fail (or waits indefinitely) since the arbiter is counted as a voting node.

For this reason, using an arbiter is not recommended if you plan to use w:majority in your application.
Please note that using an arbiter in a 3-node replica set that forms a shard in a sharded cluster is also not recommended, since chunk moves requires w:majority. Having a data-bearing node failure in one shard will be detrimental to chunk migration operations.

A: From mongoDB 5.0, w: majority is the default write concern for most MongoDB configurations. It's mostly because the value of implicit default write concern depends on your configrations.
for example, in a PSA replica sets, it's 1. but in a PSS(which is recommended) replica sets, it's value will be majority.

A: In MongoDB v5.0, the default writeConcern is w:majority.
In previous versions < v5.0, the default is writeConcern w:1


text:
Q: Proper handling of foursquare venues unicode characters in iOS app What's the proper way to handle unicode characters in an iOS app that calls the foursquare API?
Our current setup calls the foursquare API from our iOS app, and returns XML (yes, we're changing this to JSON).
While testing our app, we discovered the hard way that this foursquare location borked our app -- apparently because we did not setup to handle the two Emoji characters in the venue name.
What's the proper way to handle unicode characters at each level?
In Objective-C, as we call the foursquare API?
In our our WCF web services, as we return XML data to the app?
In SQL Server 2008, as we store a place name that may contain unicode characters?
On the database side, I know that we need to make some changes to the Collation settings, among other things.
What changes, if any, are needed to support unicode 6.1 correctly in our iOS app and web services?
Thanks!

A: I'm guessing you are trying to convert a unicode string to another encoding then back to unicode. If the converter doesn't know what the unicode character is then it could do something strange(e.g. the converter might convert one of the new sad pussycat emoji characters to a square root sign).
This might happen without you explicitly doing it depending on how you have your database setup, the XML encoding you use, your HTTP server configuration, etc.
Unicode 6.1 just adds characters, the encoding is exactly the same(i.e. some codes that didn't map to anything now map to things).


text:
Q: Want to check if one array has a value of another array, and if it does, change the value of the first array and check it again I am trying to check if one array has a value of another array, and if it does, the value of the other array should be given a number next to it. If there is a value that matches the value in the other array still, the number should be incremented until it no longer matches a value in the other array. I am struggling with this one. Any help is sincerely appreciated!
For example, "Joe" shows in the below code in both arrays. That means "Joe" in the second array should then be "Joe1". Since "Joe1" is also in the array, the "1" in "Joe1" should then be incremented to "Joe2". Any help is very much appreciated!

var arr = [{name:'Bob',num:0},{name:'Joe',num:0},{name:'Alise',num:0}];
var arr2 = [{name:'Frank',num:0},{name:'Joe',num:0},{name:'Jen',num:0},{name:'Joe1',num:0}];
var cnt = 0

arr.forEach(function(element){
  arr2.forEach(function(element2){
    if(element2.name === element.name){
       while(element2.name + element2.num === element.name){
          element2['num'] = ++cnt;
       }
       if(element2.num != 0){
        element2.name += element2.num
       }
    }
  })
})

console.log(arr2)

A:

var arr = [{name:'Bob',num:0},{name:'Joe',num:0},{name:'Alise',num:0}];
var arr2 = [{name:'Frank',num:0},{name:'Joe',num:0},{name:'Jen',num:0},{name:'Joe1',num:0}];

var arr3;
arr.forEach(e => {
    arr3 = arr2.map(e2 => {
        var name = e2.name.match(/[a-zA-Z]*/)[0]
        if (e.name === name) {
            var number = e2.name.match(/[0-9]+/)
            if (number) {
                e2.name = name + (+number[0] + 1)
            } else {
                e2.name = name + 1
            }
        }
        return e2
    })
})
console.log(arr3)


text:
Q: Tuleap error when add document We can't add document in our instance of Tuleap. Each time  we have an error.
In apache error log,  we find this error
mkdir() Permission denied in /usr/share/..../docman/include/Docman_FileStorage.class.php on line 112
I already check path and docman.inc file property
Is someone know an issu?
Thanks

A: One potential source of this error is SELinux not being set to permissive mode. A quick way to check this is by running:
# setenforce 0

at a terminal and trying to add your document. If it works, you can make this change permanent by modifying/adding:
SELINUX=enforcing

to the SELinux config file at /etc/selinux/config. HTH.

A: The user the web server is running as probably doesn't have permission to write in that directory.


text:
Q: Is it possible to rename a maven jar-with-dependencies? I'm currently using the jar-with-dependencies assembly to create such a jar.  However, the name of my jar is a bit long.
Since this jar is being used by RPG programs on an AS400, I'd like to shorten it to make life a bit easier for those developers.  But, other than by hand, I've not found a way to rename the jar from the usual project-name-version-classifier-jar-with-dependencies.jar.  I'd like something like project-name-version-classifier-full.jar
Is there anyway to do this without basically copying the jar-with-dependencies assembly descriptor and calling it full?
Additionally, I want to continue to have the jar without the classpath assembled stored in the repository.
I need two artifacts.  The jar with my classifier holding the region which the build is for.  The jar with all dependencies which also includes the region.
project-name-version-region-full.jar and project-name-version-region.jar should be stored in the repository.  In the first example the classifier is region-full, in the 2nd it's region.  The latter is working.

A: Thanks to the posts here and some digging in the maven docs I've come up with the following configuration for a general one-off repacked executable jar assembly with a custom name.
In pom.xml:
<plugin>
    <artifactId>maven-assembly-plugin</artifactId>
    <version>2.2</version>
    <executions>
        <execution>
            <id>exe</id>
            <phase>package</phase>
            <goals><goal>single</goal></goals>
            <configuration>
                <finalName>MyJarName</finalName>
                <attach>false</attach>
                <appendAssemblyId>false</appendAssemblyId>
                <descriptors>
                    <descriptor>assembly.xml</descriptor>
                </descriptors>
                <archive>
                    <manifest>
                        <mainClass>karlthepagain.MyMain</mainClass>
                    </manifest>
                </archive>
            </configuration>
        </execution>
    </executions>
</plugin>

In assembly.xml:
<assembly>
    <id>exe</id>
    <formats>
        <format>jar</format>
    </formats>
    <includeBaseDirectory>false</includeBaseDirectory>
    <dependencySets>
        <dependencySet>
            <outputDirectory>/</outputDirectory>
            <unpack>true</unpack>
            <scope>runtime</scope>
        </dependencySet>
    </dependencySets>
</assembly>

This will produce MyJarName.jar with all of its dependencies re-packaged into that same jar and the specified Main-Class: karlthepagain.MyMain.

A: It is also possible to overwrite the original jar file by using ${project.build.finalName} as final name:
<plugin>
  <artifactId>maven-assembly-plugin</artifactId>
   <executions>
      <execution>
          <phase>package</phase>
          <goals>
             <goal>single</goal>
          </goals>
      </execution>
   </executions>
   <configuration>
     <descriptorRefs>
       <descriptorRef>jar-with-dependencies</descriptorRef>
     </descriptorRefs>
     <finalName>${project.build.finalName}</finalName>
     <appendAssemblyId>false</appendAssemblyId>
   </configuration>
 </plugin>

A: I think I've found a way to configure this directly in the pom without needing a separate jar-assembly.xml.
It's basically the same as Rich's answer, except the finalName is specified with the artifactId and version.
<plugin>
    <artifactId>maven-assembly-plugin</artifactId>
    <configuration>
        <descriptorRefs>
            <descriptorRef>jar-with-dependencies</descriptorRef>
        </descriptorRefs>
        <finalName>${project.artifactId}-${project.version}-full</finalName>
        <appendAssemblyId>false</appendAssemblyId>
        <archive>
            <manifest>
                <mainClass>com.mycompany.MyMainClass</mainClass>
            </manifest>
        </archive>
    </configuration>
    <executions>
        <execution>
            <id>make-my-jar-with-dependenciess</id>
            <phase>package</phase>
            <goals>
                <goal>single</goal>
            </goals>
        </execution>
    </executions>
</plugin>

A: I'm going to give Rich the credit for pointing me in the right direction, but wanted to post the solution that worked for me as Rich's was slightly off:
My jar-assembly.xml looked like this which allowed the assembly id to change for the region which was stored as an property in my profile:
<assembly>
  <id>${env}-full</id>
    <formats>
      <format>jar</format>
    </formats>
    <includeBaseDirectory>false</includeBaseDirectory>
    <dependencySets>
      <dependencySet>
        <unpack>true</unpack>
        <scope>runtime</scope>
      </dependencySet>
    </dependencySets>
    <fileSets>
      <fileSet>
        <directory>${project.build.outputDirectory}</directory>
      </fileSet>
    </fileSets>
</assembly>

I did not use the finalName parameter in the maven-assembly-plugin settings as this built my project with my project-name-version-env-full.jar name where env-full was the classifier.
Imagine my surprise when I learned the assembly xml could be parameterized by items in the build.  This was exactly what I was looking for.

A: You can specify the finalName property to give the jar the name you want, and specify that appendAssemblyId should be false to avoid the "jar-with-dependencies" suffix.
The configuration below will output a jar called "test.jar"
<plugin>
  <artifactId>maven-assembly-plugin</artifactId>
  <version>2.2-beta-4</version>
  <executions>
    <execution>
      <id>jar-with-dependencies</id>
      <phase>package</phase>
      <goals>
        <goal>single</goal>
      </goals>
      <configuration>
        <descriptorRefs>
          <descriptorRef>jar-with-dependencies</descriptorRef>
        </descriptorRefs>
        <finalName>test</finalName>
        <appendAssemblyId>false</appendAssemblyId>
      </configuration>
    </execution>
  </executions>
</plugin>

Update: based on your comments, using the built-in descriptor won't work . I believe this is down to a bug in the recent versions of the assembly-plugin - they've removed support for classifiers, but the id is fixed if you use a built-in descriptor, so you end up with a big daft name.
As a workaround, you can copy the assembly descriptor used by the jar-with-dependencies descriptor and modify the id.
This example would result in the assembly id being appended to the finalName, so if you need to have a name of region-full.jar, you can specify the finalName as region and the assembly id as full. This will result in a file in target called region-full.jar, but note it will still be installed to the Maven repository as an attached artifact with full used as the classifier. As long as this id is different to that for your other assembly there should be no collision though.
The pom configuration would look like this.
<plugin>
  <artifactId>maven-assembly-plugin</artifactId>
  <version>2.2-beta-4</version>
  <executions>
    <execution>
      <id>jar-with-dependencies</id>
      <phase>prepare-package</phase>
      <goals>
        <goal>single</goal>
      </goals>
      <configuration>
        <descriptors>
          <descriptor>src/main/assembly/jar-assembly.xml</descriptor>
        </descriptors>
        <finalName>region</finalName>
      </configuration>
    </execution>
  </executions>
</plugin>

and the jar-assembly.xml in src/main/assembly like this:
<assembly>
  <id>full</id>
  <formats>
    <format>jar</format>
  </formats>
  <includeBaseDirectory>false</includeBaseDirectory>
  <dependencySets>
    <dependencySet>
      <unpack>true</unpack>
      <scope>runtime</scope>
    </dependencySet>
  </dependencySets>
  <fileSets>
    <fileSet>
      <directory>${project.build.outputDirectory}</directory>
    </fileSet>
  </fileSets>
</assembly>

A: This worked for me
<build>
    <finalName>anynameyoulike</finalName>
    <plugins>
        <plugin>
            <artifactId>maven-assembly-plugin</artifactId>
            <version>2.6</version>
            <configuration>
                <descriptorRefs>
                    <descriptorRef>jar-with-dependencies</descriptorRef>
                </descriptorRefs>
                <appendAssemblyId>false</appendAssemblyId>
                <archive>
                    <manifest>
                        <mainClass>com.mycompany.MyMainClass</mainClass>
                    </manifest>
                </archive>
            </configuration>
            <executions>
                <execution>
                    <id>make-assembly</id> <!-- this is used for inheritance merges -->
                    <phase>package</phase> <!-- bind to the packaging phase -->
                    <goals>
                        <goal>single</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>


text:
Q: GridView height spacing For some reason I dont understand, there is a spacing between my grid's rows while I clearly have set vertical spacing to 0. I tried playing with different width and height settings in both my grid's xml and in the image's xml (the grid component).
this is what i have:

and this is what i want:

you can see grid xml and the image xml below:
grid:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <GridView
        android:id="@+id/gridView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:columnWidth="144dp"
        android:horizontalSpacing="0dp"
        android:verticalSpacing="0dp"
        android:numColumns="auto_fit"
        android:stretchMode="spacingWidthUniform" >
    </GridView>

</RelativeLayout>

image:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/RelativeLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true" />

</RelativeLayout>

A: I guess follwoing one of the optins will solve ut issue :
set imageview.setAdjustViewBounds(true);  in adapter
Or
<GridView
        android:stretchMode="none">
</GridView>

A: Try this
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/MyGrid"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="0dp"
    android:verticalSpacing="2dp"
    android:horizontalSpacing="2dp"
    android:clipChildren="true"
    android:alwaysDrawnWithCache="true"
    android:numColumns="auto_fit"
    android:columnWidth="100dp"
    android:stretchMode="columnWidth"
    android:gravity="center_horizontal"/>


text:
Q: Stored procedure result in HTML format I require the changes in the below script so that we have to receive the results of the stored procedure sp_validatelogins as mail in HTML format.
The below is the script .
USE [test]
GO

ALTER PROC [dbo].[DBA_REPORT]
@emailrecipients NVARCHAR(256)
AS
BEGIN

SET NOCOUNT ON

DECLARE @EmailSubject NVARCHAR(128)
       ,@ReportTitle NVARCHAR(128)
       ,@ReportTitle2 NVARCHAR(128)
       ,@ReportTitle3 NVARCHAR(128)
       ,@ReportTitle4 NVARCHAR(128)
       ,@ReportTitle5 NVARCHAR(128)
       ,@ReportTitle6 NVARCHAR(128)
       ,@ReportTitle7 NVARCHAR(128)
       ,@TableHTML NVARCHAR(max)
       ,@TableHTML2 NVARCHAR(max)
       ,@TableHTML3 NVARCHAR(max)
       ,@TableHTML4 NVARCHAR(max)
       ,@TableHTML5 NVARCHAR(max)
       ,@TableHTML6 NVARCHAR(max)
       ,@TableHTML7 NVARCHAR(max)
       ,@Mergedtable NVARCHAR(MAX)
       ,@sql nvarchar(max)

SET NOCOUNT ON

BEGIN
       SELECT  @EmailSubject = 'DBA REPORT'
              ,@ReportTitle =  'Report of jobs that failed in the past 24 hours'
              ,@ReportTitle2 = 'Report of disabled jobs'
              ,@ReportTitle3 = 'Invalid Logins'
              ,@ReportTitle4 = 'Logins having no permissions'
              ,@ReportTitle5 = 'Logins having sysadmin permissions'
              ,@ReportTitle6 = 'Report on Suspect Pages'
              ,@ReportTitle7 = 'Report on databases'

--3rd.create TEMP TABLE to hold results of SP call
          create table #invalidlogins(
                                       A_SID varchar(128),
                                       A_LOGIN varchar(128))

           insert into #invalidlogins
           exec sp_validatelogins

--select from the table variable Only if the data exists

IF EXISTS (SELECT * FROM #invalidlogins)
 BEGIN

---Creating  HTML table
              SET @TableHTML3 = '' + '
'
               + @ReportTitle3 + '
' + '

' + '
'
               + 'A_LOGIN
'

              DECLARE @EmailBody3 NVARCHAR(max)

              SELECT @EmailBody3 = (
                           SELECT td =A_SID
                                  ,td =A_LOGIN
                           FROM #invalidlogins
                           FOR XML RAW('tr')
                                  ,ELEMENTS
                           )

              SET @EmailBody3 = REPLACE(@EmailBody3, '', '')
              SET @EmailBody3 = REPLACE(@EmailBody3, '	', '	')
              SET @EmailBody3 = REPLACE(@EmailBody3, '_x0020_', SPACE(1))
              SET @EmailBody3 = REPLACE(@EmailBody3, '_x003D_', '=')
              SET @EmailBody3 = REPLACE(@EmailBody3, '<TRRow>0</TRRow>', '')

              SET @TABLEHTML3 = @TABLEHTML3 + @EmailBody3 + '

'
              SET @TABLEHTML3 = '
' + @TableHTML3 + '
'

              DROP TABLE #invalidlogins

 -- Send the mail in this block as well.
    END

         SET @Mergedtable = @TableHTML+@TableHTML2+@TableHTML3+@TableHTML5+@TableHTML7

       EXEC msdb.dbo.sp_send_dbmail @profile_name = 'SQLDBA Profile'
                     ,@recipients = @emailrecipients
                     ,@Body = @Mergedtable
                     ,@subject = @EmailSubject
                     ,@Body_format = 'HTML'

  END

END

GO

A: I found some years ago a query that can transform any query into HTML:
-- Description: Turns a query into a formatted HTML table. Useful for emails.
-- Any ORDER BY clause needs to be passed in the separate ORDER BY parameter.
-- =============================================
CREATE PROC [dbo].[spQueryToHtmlTable]
(
  @query nvarchar(MAX), --A query to turn into HTML format. It should not include an ORDER BY clause.
  @orderBy nvarchar(MAX) = NULL, --An optional ORDER BY clause. It should contain the words 'ORDER BY'.
  @html nvarchar(MAX) = NULL OUTPUT --The HTML output of the procedure.
)
AS
BEGIN
  SET NOCOUNT ON;

  IF @orderBy IS NULL BEGIN
    SET @orderBy = ''
  END

  SET @orderBy = REPLACE(@orderBy, '''', '''''');

  DECLARE @realQuery nvarchar(MAX) = '
    DECLARE @headerRow nvarchar(MAX);
    DECLARE @cols nvarchar(MAX);

    SELECT * INTO #dynSql FROM (' + @query + ') sub;

    SELECT @cols = COALESCE(@cols + '', '''''''', '', '''') + ''['' + name + ''] AS ''''td''''''
    FROM tempdb.sys.columns
    WHERE object_id = object_id(''tempdb..#dynSql'')
    ORDER BY column_id;

    SET @cols = ''SET @html = CAST(( SELECT '' + @cols + '' FROM #dynSql ' + @orderBy + ' FOR XML PATH(''''tr''''), ELEMENTS XSINIL) AS nvarchar(max))''

    EXEC sys.sp_executesql @cols, N''@html nvarchar(MAX) OUTPUT'', @html=@html OUTPUT

    SELECT @headerRow = COALESCE(@headerRow + '''', '''') + '''' + name + ''	''
    FROM tempdb.sys.columns
    WHERE object_id = object_id(''tempdb..#dynSql'')
    ORDER BY column_id;

    SET @headerRow = ''
'' + @headerRow + ''
'';

    SET @html = ''
'' + @headerRow + @html + ''
'';
    ';

  EXEC sys.sp_executesql @realQuery, N'@html nvarchar(MAX) OUTPUT', @html=@html OUTPUT
END
GO
-----------------------------------------------------
USAGE:

DECLARE @html nvarchar(MAX);
EXEC spQueryToHtmlTable @html = @html OUTPUT,  @query = N'SELECT * FROM dbo.People', @orderBy = N'ORDER BY FirstName';

EXEC msdb.dbo.sp_send_dbmail
    @profile_name = 'Foo',
    @recipients = 'bar@baz.com;',
    @subject = 'HTML email',
    @body = @html,
    @body_format = 'HTML',
    @query_no_truncate = 1,
    @attach_query_result_as_file = 0;

A: If exec sp_validatelogins does not return a resultset, the #invalidlogins will be empty.
As a result, setting @EmailBody to values in the #invalidlogins table will also set @EmailBody to NULL. The same is true for @TableHTML
     SET @TABLEHTML = @TABLEHTML + @EmailBody + '

'

This might be why you are receiving empty mails.
You could resolve this by inserting the 'No Invalid Logins' value instead of selecting it:
IF EXISTS (SELECT * FROM #invalidlogins)
BEGIN
SELECT A_LOGIN as Invalid_Logins FROM #Invalidlogins
END
ELSE BEGIN
INSERT INTO #invalidlogins(A_LOGIN)
SELECT 'No Invalid Logins' as Invalid_logins
END

Result for  @EmailBody

No Invalid Logins

Result for  @TableHTML

bla

A_LOGIN

No Invalid Logins

Or you could not send an alert if the procedure does not return anything.
Edit 2

If there is no data i should not receive any mail but i'm receiving
  empty mail so what i need to change to not receive any mail if no data
  exist

Then you should specify
IF EXISTS (SELECT * FROM #invalidlogins)  BEGIN

--Run all following statements & send the mail

END

such as
USE [test]
GO

ALTER PROC [dbo].[DBA_REPORT]
@emailrecipients NVARCHAR(256)
AS
BEGIN

SET NOCOUNT ON

DECLARE @EmailSubject NVARCHAR(128)
       ,@ReportTitle NVARCHAR(128)
       ,@ReportTitle2 NVARCHAR(128)
       ,@ReportTitle3 NVARCHAR(128)
       ,@ReportTitle4 NVARCHAR(128)
       ,@ReportTitle5 NVARCHAR(128)
       ,@ReportTitle6 NVARCHAR(128)
       ,@ReportTitle7 NVARCHAR(128)
       ,@TableHTML NVARCHAR(max)
       ,@TableHTML2 NVARCHAR(max)
       ,@TableHTML3 NVARCHAR(max)
       ,@TableHTML4 NVARCHAR(max)
       ,@TableHTML5 NVARCHAR(max)
       ,@TableHTML6 NVARCHAR(max)
       ,@TableHTML7 NVARCHAR(max)
       ,@Mergedtable NVARCHAR(MAX)
       ,@sql nvarchar(max)

SET NOCOUNT ON

       SELECT  @EmailSubject = 'DBA REPORT'
              ,@ReportTitle =  'Report of jobs that failed in the past 24 hours'
              ,@ReportTitle2 = 'Report of disabled jobs'
              ,@ReportTitle3 = 'Invalid Logins'
              ,@ReportTitle4 = 'Logins having no permissions'
              ,@ReportTitle5 = 'Logins having sysadmin permissions'
              ,@ReportTitle6 = 'Report on Suspect Pages'
              ,@ReportTitle7 = 'Report on databases'

--3rd.create TEMP TABLE to hold results of SP call
          create table #invalidlogins(
                                       A_SID varchar(128),
                                       A_LOGIN varchar(128))

           insert into #invalidlogins
           exec sp_validatelogins

--select from the table variable Only if the data exists

IF EXISTS (SELECT * FROM #invalidlogins)
 BEGIN

---Creating  HTML table
              SET @TableHTML3 = '' + '
'
               + @ReportTitle3 + '
' + '

' + '
'
               + 'A_LOGIN
'

              DECLARE @EmailBody3 NVARCHAR(max)

              SELECT @EmailBody3 = (
                           SELECT td =A_SID
                                  ,td =A_LOGIN
                           FROM #invalidlogins
                           FOR XML RAW('tr')
                                  ,ELEMENTS
                           )

              SET @EmailBody3 = REPLACE(@EmailBody3, '', '')
              SET @EmailBody3 = REPLACE(@EmailBody3, '	', '	')
              SET @EmailBody3 = REPLACE(@EmailBody3, '_x0020_', SPACE(1))
              SET @EmailBody3 = REPLACE(@EmailBody3, '_x003D_', '=')
              SET @EmailBody3 = REPLACE(@EmailBody3, '<TRRow>0</TRRow>', '')

              SET @TABLEHTML3 = @TABLEHTML3 + @EmailBody3 + '

'
              SET @TABLEHTML3 = '
' + @TableHTML3 + '
'

              DROP TABLE #invalidlogins

         SET @Mergedtable = @TableHTML+@TableHTML2+@TableHTML3+@TableHTML5+@TableHTML7

       EXEC msdb.dbo.sp_send_dbmail @profile_name = 'SQLDBA Profile'
                     ,@recipients = @emailrecipients
                     ,@Body = @Mergedtable
                     ,@subject = @EmailSubject
                     ,@Body_format = 'HTML'

     -- Send the mail in this block as well.
    END

END

GO


text:
Q: How to define the pen width in the menu bar I am trying to write the code for my own paint program. I have added the menu for few basic color options. Now I would like to add the same menu style pen width option (e.g. 5, 10, according to the user's choice). But I'm stuck here. Please advise, Thanks!
Here I am importing libraries
     from tkinter import *
     import tkinter as tk
     from tkinter import Tk, Canvas, Frame, BOTH
     import turtle

     current_x, current_y = 0,0
     color = 'black'
     width = 10

Then Define functions
     def locate_xy(event):
        global current_x, current_y
        current_x, current_y = event.x, event.y

     def addLine(event):
         global current_x, current_y
         canvas.create_line((current_x, current_y, event.x, event.y), fill=color, width=width)
         current_x, current_y = event.x, event.y

    def show_color(new_color):
        global color
        color = new_color

    def new_canvas():
        canvas.delete('all')
        display_pallete()

Plot Canvas and setup menus
    root = Tk()
    canvas = Canvas()

    root.rowconfigure(0, weight=1)
    root.columnconfigure(0, weight=1)

    menubar = Menu(root)
    root.config(menu = menubar)
    submenu = Menu(menubar, tearoff=0)

Here I define menu lines and here I am stuck
    menubar.add_cascade(label='File', menu=submenu)
    submenu.add_command(label='Novo okno', command=new_canvas)
    submenu.add_command(label='Velikost')
    **submenu.add_command(label='5', command=width)** ?????????

    canvas=Canvas(root, background='white')
    canvas.grid(row=0,column=0, sticky='nsew')

    canvas.bind('<Button-1>',locate_xy)
    canvas.bind('<B1-Motion>', addLine)

Here is the color pallete
    def display_pallete():
        id = canvas.create_rectangle((10, 10,30,30), fill='black')
        canvas.tag_bind(id, '<Button-1>', lambda x: show_color('black'))

        id = canvas.create_rectangle((10, 40,30,60), fill='gray')
        canvas.tag_bind(id, '<Button-1>', lambda x: show_color('gray'))

        id = canvas.create_rectangle((10, 70,30,90), fill='brown4')
        canvas.tag_bind(id, '<Button-1>', lambda x: show_color('brown4'))

        id = canvas.create_rectangle((10, 100,30,120), fill='red')
        canvas.tag_bind(id, '<Button-1>', lambda x: show_color('red'))

        id = canvas.create_rectangle((10, 130,30,150), fill='orange')
        canvas.tag_bind(id, '<Button-1>', lambda x: show_color('orange'))

        id = canvas.create_rectangle((10, 160,30,180), fill='yellow')
        canvas.tag_bind(id, '<Button-1>', lambda x: show_color('yellow'))

        id = canvas.create_rectangle((10, 190,30,210), fill='green')
        canvas.tag_bind(id, '<Button-1>', lambda x: show_color('green'))

        id = canvas.create_rectangle((10, 220,30,240), fill='blue')
        canvas.tag_bind(id, '<Button-1>', lambda x: show_color('blue'))

        id = canvas.create_rectangle((10, 250,30,270), fill='purple')
        canvas.tag_bind(id, '<Button-1>', lambda x: show_color('purple'))

        id = canvas.create_rectangle((10, 280,30,300), fill='darkred')
        canvas.tag_bind(id, '<Button-1>', lambda x: show_color('darkred'))

        id = canvas.create_rectangle((10, 310,30,330), fill='coral')
        canvas.tag_bind(id, '<Button-1>', lambda x: show_color('coral'))

        id = canvas.create_rectangle((10, 340,30,360), fill='orangered')
        canvas.tag_bind(id, '<Button-1>', lambda x: show_color('orangered'))

        id = canvas.create_rectangle((10, 370,30,390), fill='lawngreen')
        canvas.tag_bind(id, '<Button-1>', lambda x: show_color('lawngreen'))

        id = canvas.create_rectangle((10, 400,30,420), fill='limegreen')
        canvas.tag_bind(id, '<Button-1>', lambda x: show_color('limegreen'))

        id = canvas.create_rectangle((10, 430,30,450), fill='springgreen')
        canvas.tag_bind(id, '<Button-1>', lambda x: show_color('springgreen'))

        id = canvas.create_rectangle((10, 460,30,480), fill='seagreen')
        canvas.tag_bind(id, '<Button-1>', lambda x: show_color('seagreen'))

        id = canvas.create_rectangle((10, 490,30,510), fill='cyan')
        canvas.tag_bind(id, '<Button-1>', lambda x: show_color('cyan'))

        id = canvas.create_rectangle((10, 520,30,540), fill='teal')
        canvas.tag_bind(id, '<Button-1>', lambda x: show_color('teal'))

        id = canvas.create_rectangle((10, 550,30,570), fill='powderblue')
        canvas.tag_bind(id, '<Button-1>', lambda x: show_color('powderblue'))

        id = canvas.create_rectangle((10, 580,30,600), fill='navy')
        canvas.tag_bind(id, '<Button-1>', lambda x: show_color('navy'))

        id = canvas.create_rectangle((10, 610,30,630), fill='slateblue')
        canvas.tag_bind(id, '<Button-1>', lambda x: show_color('slateblue'))

        id = canvas.create_rectangle((10, 640,30,660), fill='lavender')
        canvas.tag_bind(id, '<Button-1>', lambda x: show_color('lavender'))

        id = canvas.create_rectangle((10, 670,30,690), fill='violet')
        canvas.tag_bind(id, '<Button-1>', lambda x: show_color('violet'))

        id = canvas.create_rectangle((10, 700,30,720), fill='darkviolet')
        canvas.tag_bind(id, '<Button-1>', lambda x: show_color('darkviolet'))

        id = canvas.create_rectangle((10, 730,30,750), fill='peru')
        canvas.tag_bind(id, '<Button-1>', lambda x: show_color('peru'))

        id = canvas.create_rectangle((10, 760,30,780), fill='white')
        canvas.tag_bind(id, '<Button-1>', lambda x: show_color('white'))

    display_pallete()

    # Open window having dimension 100x100

    root.geometry('2000x1000')
    root.configure(bg='aqua')
    root.title("Risalni stroj")

    root.mainloop()


text:
Q: Animated cursor wont work in my web application can anyone help me how to make my downloaded animated cursor work in my web application im using chrome by the way as my default browser.
My problem is the animated cursor wont show in my web application.
<style type="text/css">
body{
cursor: url(cursor/lightning.ani), auto;
}
</style>

A: I believe getting rid of the , auto. From my experience with Anicursor, it is unnecessary in most situations.

A: First turn the file into a .gif cursor: url(cursor/lightning.gif), auto; but it will not be animated. It is supported in Chrome and firefox but not in IE (internet explorer)


text:
Q: How set focus on specific input text field in Flutter I have some TextFormField field in my flutter app. Here are the controllers of those fields.
TextEditingController nameCtrl = TextEditingController();
TextEditingController idCtrl = TextEditingController();
TextEditingController nodeCtrl = TextEditingController();
TextEditingController unitCodeCtrl = TextEditingController();

I want to set focus to the unitCodeCtrl text field programmatically when an event fired (on button click) but can not figure out how can I do that.
...,
onPressed:(){
  //what can i do for set focus to unitcode text field?
}

A: First declare a focus node like this
final FocusNode unitCodeCtrlFocusNode = FocusNode();

then assign this focus node to that textfield
TextFormField(
     controller: unitCodeCtrl,
     focusNode: unitCodeCtrlFocusNode,
)

And on the button click call below method, this will set a focus
onPressed:(){
  FocusScope.of(context).requestFocus(unitCodeCtrlFocusNode);
}

or
onPressed:(){
  unitCodeCtrlFocusNode.requestFocus();
}


text:
Q: Sorting Minutes im trying to sort soccer minutes, but is not sorting right, for example in soccer is very normal minutes be like "1,2,3,40+5...". Basically is saying 40 minutes + 5 minutes (45 minutes).
So in my records i a colllection like:
[
  {
    "id": 9876,
    "minute": "90+30",
  },
  {
    "id": 9874,
    "minute": "90+10",
  },
  {
    "id": 9873,
    "minute": "105",
  },
  {
    "id": 9873,
    "minute": "90",
  },
 ...
]

So to make it order the minutes right, i need to use explode on the string "minute", than make a array_sum, but in my code, it still doesnt order right, still in the 105 is above of "90+10".
Here is my code:
$timelines = SoccerTime::where('match_id',$id)
        ->orderBy('minute', 'desc')
        ->get();
$collection = collect($timelines);
$sorted = $collection->sortByDesc('minute');
$test = $sorted->values()->all();

//Here i begin the new Sort
$newSort =  collect($test)->sort(function ($a, $b) {
    return array_sum(explode("+",$a->minute)) -  array_sum(explode("+",$b->minute));
});
return  $newSort;

A: I think you should change a couple of field in your model. I'd use a minute field to store the actual minute (100 in cases like your "90+10" example) and another integer field period to indicate the "period", where:
- 1 for 1T
- 2 for 2T
- 3 for 1ET
- 4 for 2ET.
So your new way of sorting should be:
First by period (solving your problem of getting 90'+4' of 2T before 93' of 1ET) and then by minute (the actual sort).
It would be so much easier and it could also help you to do some other reporting queries.


text:
Q: Cannot use border-radius CSS3 property with Flying Saucer I am working on a project where I need to convert an HTML to a PDF. I am using Flying Saucer 9.1.6 from Maven Central for this. The subjacent PDF generation library is IText 2.1.7.
Although Flying Saucer Git repo states that it supports CSS3 border-radius syntax I am unable to achieve rounded corners with border-radius.
Here is the sample code
ITextRenderer pdfRenderer = new ITextRenderer();
String resumeHTML = "\n" +
            "\n" +
            "  <title>JS Bin</title>\n" +
            "    \n" +
            "\n" +
            "\n" +
            "  \n" +
            "  \n" +
            "\n" +
            "";
    pdfRenderer.setDocumentFromString(resumeHTML);
    pdfRenderer.layout();
    FileOutputStream fos = new FileOutputStream("sample.pdf");
    pdfRenderer.createPDF(fos);
    fos.flush();
    fos.close();

Valid HTML snippet used in the above sample

  <title>JS Bin</title>

Can anybody suggest a way to achieve rounded corners when using Flying Saucer?

A: border-radius works fine with divs, so you can use a div, and add your image with background-image:

<title>JS Bin</title>


text:
Q: Creating plots in R with 3 variables I had been following the analysis steps in the Little Book of R. It is a great tutorial but for things to work, it and many other tutorials need to have the data organized a certain way.
My data is structured like this (a very tiny tiny sample)a:
Phylum Confidence Time Seq_ID Environment Dataset
Acidobacteria 0.801 5 >3134898 Marine 4440037.3
Bacteroidetes 0.812 6 >3066473 Marine 4440037.3
Acidobacteria 0.828 5 >3085551 Gut 4440038.3
Firmicutes    0.830 4 >3087676 Coral 4440036.3

I want a good way to
a) Plot the Time by bacterial phylum for each environment. I realize that this means I will need to created a plot for each phylum. (see plots)
b. Plot the time by environment of two different phyla which I will then color code by environment. (see plots)
I know I can create a new dataframe based on an environment and bacteria, but I have not been able to incorporate it correctly into a plot that uses a third variable (time).
new_df = myDF[(myDF$Environment=='Marine') & (myDF$Phylum=='Acidobacteria'),]

I have tried several things...
p <- ggplot(myDF, aes(Environment, Time))
p + geom_boxplot(aes(fill = Environment))

It creates a plot, but this does not take into consideration the phylum (e.g. I would like a separate plot for each phylum).
Or this...
 for (i in environment) #this is a list I created
 {
     for (j in phyla) #this is a list I created
     {
        #stats_df = myDF[(myDF$Environment==i) & (myDF$Phylum==j),]
        plot(myDF[[j]], myDF[[i]], xlab=NULL, ylab='Time')
      }
 }

This one gets errors
Warning in min(x) : no non-missing arguments to min; returning Inf
Warning in max(x) : no non-missing arguments to max; returning -Inf
Warning in min(x) : no non-missing arguments to min; returning Inf
Warning in max(x) : no non-missing arguments to max; returning -Inf
Error in plot.window(...) : need finite 'xlim' values
Calls: plot -> plot.default -> localWindow -> plot.window
Execution halted

shell returned 1

But even if it did plot, it still does not take into consideration the Time variable. What I am really trying to figure out is how to use three variables in a plot.

A: Assuming phylum is a factor variable
library(ggplot2)
g<- ggplot(myDF, aes(Environment, Time))
g + geom_point() + facet_grid(. ~ phylum)

 library(ggplot2)

 g<- ggplot(df1, aes(Environment, Time))
 g + geom_point() + facet_grid(phylum ~ .)

Please see here for the details.


text:
Q: Will Brew MP Run without Sourcery G++ ARM Compiler? can I compile & run  Brew MP Applications without Sourcery G++ ARM Compiler?

A: Yes you can compile and run Brew MP application without an ARM compiler as long as you're just developing for the Brew MP Simulator
In order to run Brew MP applications on the simulator you will need a compiler that can generate X86 binaries. You can use Sourcery G++/X86 or Visual Studio/Express to do this.
To run the application on a device you will need an ARM compiler. You can use a GNU based compiler such as Sourcery G++ ARM compiler, a commercial ARM compiler, or any compatible ARM compiler for this purpose. But not all compilers are tested and supported.


text:
Q: Revision control locking: Is the jury still out? When I'm online it seems that everyone has agreed that using the exclusive locking workflow in source control is a Bad Thing. All the new revision control systems I see appear to be built for edit and merge workflows, and many don't even support exclusive locks at all.
However, everyone I work with is of the opinion that exclusive locks are a "must have" for any source control system, and working any other way would be a nightmare. Even recent hires from other companies seem to come in with this idea.
My question isn't who is right. I'm pretty sure what answer I'd get to that. My question is, is there really still any debate over this matter? Is there an honest "pro locking" camp out there that makes a serious case? Is any work being done to advance the art of revision control based around the locking model? Or are locking fans flogging a dead horse?
EDIT:
The answers so far have done a good job of explaining why exclusive locks are a good feature to use occasionally. However, I'm talking about promoting a workflow where exclusive locks are used for everything.

A: I like having the option to exclusive-lock some file[s].
Having an exclusive lock is necessary, e.g. for binary files.
It's also semi-necessary for some machine-generated non-binary files (e.g. for Visual Studio project files, which don't 'merge' at all well if ever there are two parallel changes to be merged).

A: If you believe that merges are hard (and while we've come a long way, they can be in some circumstances), and you don't have programmers frequently wanting to edit the same file, exclusive locking isn't necessarily that bad.
I wouldn't use them on an open source project, obviously, but in the corporate world where the rules are stricter and you can walk over to a guy and say "can I break your lock?", it gives visibility into what people are working on and avoids conflicts so they don't have to be resolved later.
If two people really need to work on a file at the same time, often you can branch that file, and so long as the tool makes it clear that that branch needs to be merged back in, you can do that and resolve any conflicts then.
That said, I don't think I want to have to work in an exclusive locking world again.

A: Exclusive locking is the best you can do in a worst-case scenario, so its presence always tells me that there are bigger problems.
One of those bigger problems is bad organization of code.  On one of my consulting gigs for a major telecomm, eight out of thirty team members were constantly working on the same source file (a VB.NET "god" form).  We would wait for someone else to finish their work and release the exclusive lock (VSS), then the next person in the pecking order would immediately lock the file to apply their changes.  This took forever because they had to reintegrate all their work into the new code that they could see only just then.  Since I was the new guy, I was on the bottom of the pecking order and I NEVER was allowed to check in my code changes.  I eventually went to the project manager/director and suggested that I be tasked with another part of the application functionality.  This project eventually self-destructed, but most of us left as we realized that inevitability.  Note that the use of VSS integration was a crucial part of this failure, too, since it forces early acquisitions of that precious file lock.
So, a well-organized project should almost never result in two people working on the same part of the same source file at the same time.  Therefore, no need for exclusive locking.
Another of those bigger problems is putting binary files into source control.  Source control tools are not designed to handle binaries, and that is a good thing.  Binaries require different treatment, and source control tools cannot support that special treatment.  Binaries must be managed as a whole, not as parts (lines).  Binaries tend to be far more stable/unchanging.  Binaries tend to need explicit versioning different from source control versioning, often with multiple versions available simultaneously.  Binaries are often generated from source, so only the source needs to be controlled (and the generation scripts).  See Maven repositories for a binary-friendly storage design (but please don't use Maven itself, use Apache Ivy).

A: The arguments for locking are really bad. They basically say: our tools are so bad they cannot merge, so we lock.

A: In my experience, it's often necessary for two people to work on the same file at the same time.  (There are, presumably, shops where this doesn't happen, but I have fairly varied experience to draw on.)
In these cases, it is necessary for both people to get copies of the original, do their work, and merge their changes.  In non-locking VCSs, this is done automatically and accurately for the most part.
With a locking VCS, what happens is that one person gets the lock.  If that person finishes first, great; if not, the other person gets to wait before being able to introduce changes.  Sometimes it is necessary to make a quick bug fix while somebody is in the middle of a long change process, for example.  Once the second person has the lock, the second person needs to merge the changes, typically manually, and check in the new version.  On several occasions, I've seen the first person changes dropped entirely, as the second person didn't bother with the manual merge.  Frequently this merge is done hastily, either out of distaste for the job or simple time pressure.
Therefore, if two people need to work on the same file at the same time, a non-locking VCS is almost always better.
If this doesn't come up, and two people never need to work on the same file at the same time, it doesn't matter which you use.

A: Here's my $0.02.
Locking is an old school of thought for textual Code. Once programmers use merging a couple of times they learn and usually like the power of it.
Valid cases for locks still exist.

*

*Graphics alterations. 99% of the time you cannot merge 2 peoples work on the same graphic.

*Binary updates.

*Sometimes code can be complex/simple enough to justify only 1 person working on it at a time. In this case it's a project management choice to use a feature.

A: On an open-source project like a game, it makes sense to keep images under revision control, and those are nice to be able to lock (Subversion supports this).  For source files, it's better to get into the edit-merge work flow.  It's not hard and increases productivity in my experience.

A: Interesting question. To me, the issue is not so much whether to lock, but how long to lock. In this shop, I'm a minority of one, because I like to merge. I like to know what other people have done to to the code. So what I do is:

*

*Always work in a local copy of the source tree.

*Run Windiff often against the "official" code and if necessary merge changes down to my local copy. For merging, I use an old Emacs (Epsilon) and have the compare-buffers command bound to a hot-key. Another key says "make the rest of this line like the one in the other file", because many changes are small.

*When I'm ready to check in changes, Windiff tells me what files I need to lock, check in, and unlock. So I keep them locked as short a time as possible, like minutes.
So when Fearless Leader says "Have you checked in your code?" the answer is "I don't have any checked out."
But as I said, I'm a minority of one.

A: In my opinion, the main reason people use exclusive locking is its simplicity and for them, lack of risk.
If I have exclusive access to a file, I won't have to try and understand someone elses changes to the same file. I don't have to risk making my changes and then having to merge with someone elses when I check in.
If I have an exclusive lock on the files I'm changing, then I know that when I checkin, I will be able to checkin a coherent changeset; it is simpler for me to do this.
The other aspect of merging (esp. automatic merging) is the potential for regression problems. Without good automated tests, every time you do a automatic merge, you may get problems. At least if you have an exclusive lock on something you ensure that someone is looking at the code before it's checked in. This, for some, reduces risk.
What exclusive locking takes away is the potential parallelism of changes. You can't have two people working on a file.
The open source model (lots of people around the world collaborating on different stuff) has promoted the view that locking is bad, but it really does work for some teams. It does avoid real problems. I'm not saying that these problems can't be overcome, but it requires a change in behaviour for people; if you want to change to a non-locking model, you have to persuade them to change to a way of working which can seem harder for them, and can actually (in their view) increase risk  cause regressions.
Personally, I prefer not to use locks, but I can see why some people don't like it.

A: A bit late to this discussion but to anybody who has read and digested Steve Maguire's Writing Solid Code a central point is to have your tools detect and identify as many problems as possible.
A compiler doesn't get tired after 12 or more straight hours and forget to issue a syntax error.  But it is quite easy to forget a manual step of initiating a communication and paying for it later.
If you need to version control a binary file then you need some form of locking to prevent - or at least warn of - an accidental overwrite.  It must be a fundamental feature of any VCS even a distributed one.  To use such a feature in a DVCS may require the creation of a central repository but is that so evil?  If you use a DVCS in any sort of corporate environment, you will have a central repo to ensure business continuity.

A: If you're used to exclusive locking, then it's hard to embrace the edit-merge workflow.
Exclusive locking has its benefits, especially for binary files (images, videos, ...) which can't be merged automatically or not at all.
But: the need for exclusive locking always indicates another problem: good communication between people working on the project. Exclusive locking provides a poor replacement: it tells users that someone else is already working on that particular file - something they should know without using a version control system.
Since there are better ways to help with the communication among team members, most (all?) version control systems don't implement exclusive locking anymore or just a reduced version (i.e., locking, but such that those locks are not enforced).
It's not the job of a version control system to help with the communication.

A: Addressing your edit comments.
Even RCS and SCCS (the grandfather VCS for most of what runs on Unix/Linux these days) permit concurrent editing access to files, and I'm not referring to separate branches.  With SCCS, you could do 'get -k SCCS/s.filename.c' and obtain an editable copy of the file -- and you could use an option ('-p' IIRC) to get it to standard output.  You could have other people doing the same.  Then, when it came time to check-in, you'd have to ensure that you started with the correct version or do a merge to deal with changes since your starting version was collected, etc.  And none of this checking was automated, and conflicts were not handled or marked automatically, and so on.  I didn't claim it was easy; just that it could be done.  (Under this scheme, the locks would only be held for a short time, while a checkin/merge was in progress.  You do have locks still - SCCS requires them, and RCS can be compiled with strict locking required - but only for short-ish durations.  But it is hard work - no-one did it because it is such hard work.)
Modern VCS handle most of the issues automatically, or almost automatically.  That is their great strength compared to the ancestral systems.  And because merging is easy and almost automatic, it allows different styles of development.
I still like locking.  The main work system I use is (IBM Rational) Atria ClearCase; for my own development, I use RCS (having given up SCCS around Y2K).  Both use locking.  But ClearCase has good tools for doing merging, and we do a fair amount of that, not least because there are at least 4 codelines active on the product I work on (4 main versions, that is).  And bug fixes in one version quite often apply to the other versions, almost verbatim.
So, locking-only VCS typically do not have good enough merge facilities to encourage the use of concurrent editing of files.  More modern VCS have better merging (and also branching) facilities, and therefore do not have as strong a need for locking for more than the shortest term (enough to make the operations on the file - or files in the more advanced systems - atomic).


text:
Q: I tried many codes to merge meltiple data frames together in R, but always get error Update: problem sloved, I shouldn't name the variable name as '2013'
I have some data frames, I want to merge them together, but always get an error. I want to merge them by the variable ('Date' and 'Time'), each data frame has the same value for 'Date' and 'Time'.
This is what I have tried:
> list2013 <- list(data1, data2, data3, data4, data5, data6, data7)
> 2013 <- Reduce(function(x, y) merge(x, y, all = TRUE), list2013, accumulate = FALSE)

Error in 2013 <- Reduce(function(x, y) merge(x, y, all = TRUE), list2013,
:  invalid (do_set) left-hand side to assignment

The data frames look like this:
head(data1)
        Date  Time  Value_1
1 01/01/2013 00:00     84
2 01/01/2013 00:15     71
3 01/01/2013 00:30     73
4 01/01/2013 00:45     73
5 01/01/2013 01:00     73
6 01/01/2013 01:15     80

 head(data2)
        Date  Time  Value_2
1 01/01/2013 00:00      38
2 01/01/2013 00:15      29
3 01/01/2013 00:30      27
4 01/01/2013 00:45      32
5 01/01/2013 01:00      36
6 01/01/2013 01:15      40

head(data3)
        Date  Time  Value_3
1 01/01/2013 00:00      23
2 01/01/2013 00:15      13
3 01/01/2013 00:30      11
4 01/01/2013 00:45      21
5 01/01/2013 01:00      27
6 01/01/2013 01:15      31

The expected output looks like this:
      Date  Time  Value_1  Value_2  Value_3
1 01/01/2013 00:00     84      38        23
2 01/01/2013 00:15     71      29        13
3 01/01/2013 00:30     73      27        11
4 01/01/2013 00:45     73      32        21
5 01/01/2013 01:00     73      36        27
6 01/01/2013 01:15     80      40        31

A: Is there a need to call an anonymous function here? Can we just call merge directly in the Reduce function?
z <- data.frame(id = c(1,2,3,4),a =c(1,2,3,4), b0 = c(4,3,2,1))
x <- data.frame(id = c(1,2,3,4),a =c(1,2,3,4), b3 = c(6,3,2,1))
y <- data.frame(id = c(1,2,3,4),a =c(1,2,3,4), z1 = c(4,3,2,1))

l <- list(x,y,z)

Reduce(merge, l)

#output
 id a b3 z1 b0
  1 1  6  4  4
  2 2  3  3  3
  3 3  2  2  2
  4 4  1  1  1


text:
Q: Hugin crashes before creating the panorama When I try to create a panorama with Hugin on OS X, it crashes with the following error message:
External program open not found in the bundle, reverting to system path

What does this error message mean and how to fix it?

A: After some digging in the Hugin source code, I found out that the message should in fact be "External program PTBatcherGui not found in the bundle, reverting to system path", but the authors somehow hard-coded "open" instead of "PTBatcherGui" resulting in this poor error message.
So the solution is simply to install PTBatcherGui.app. It should be in the same .dmg as Hugin.app. Move it next to Hugin.app and the error message and crash should be gone.


text:
Q: Access contacts filters The contacts on the android phone come with settings like "Filter Contacts" that lets the user set things like "Show only contacts that have phone numbers" and "Only show contacts that are online", and which sets of contacts to display (eg, phone only, phone and google etc.).
When doing this
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
startActivityForResult(intent, PICK_CONTACT);

is there any way to get those filters applied to the contacts list?  By default it seems to return everything.  If you can't, is there some way to access those settings to see what they are, so I can build my own contacts picker list to match how the phone user has set their default?  This only needs to work for Android 2 up.
(The ideal option would be a way to invoke the contact picker that lets the user also set the filters from in there.)

A: I think if you pass a URI to the intent like the one shown here, you should be able to apply your filter. So you'd do something like this:
Intent intent = new Intent(Intent.ACTION_PICK, PhoneLookup.CONTENT_FILTER_URI);
intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
startActivityForResult(intent, PICK_CONTACT);


text:
Q: Need help updating database row with values from HTML form I've got an admin area where the admins can set the level of repair and it shows on a progress bar in the users area. I have it all working apart from updating the mySQL database to the value submitted.
My database has a table called 'users' and fields 'UserID', 'Username', 'Password', 'progress', 'admin'.
Here is the code I'm using to try and make the magic happen:
<?php
$query="SELECT * FROM users";
$result=mysql_query($query);
$num=mysql_numrows($result);

?>
<form id="chooseuseredit" method="post" action="<?php echo $PHP_SELF;?>">
<select name="ChooseUser">
<?php
$i=0;
while ($i < $num) {

$f1=mysql_result($result,$i,"UserID");
$f2=mysql_result($result,$i,"Username");
$f3=mysql_result($result,$i,"progress");
$f4=mysql_result($result,$i,"admin");
?>

<option value="<?php echo $f1; ?>"><?php echo $f2; ?></option>

<?php
$i++;
}
?>
</select>
<input type="submit" name="chooseSubmit" id="chooseSubmit" value="Choose User" />
</form>
<?php
if(isset($_POST['chooseSubmit']) )
{
  $varID = $_POST['ChooseUser'];
  $errorMessage = "Jesus Christ Benton, Choose a User!!";

?>

Editing UserID: <?php echo "$varID"; ?>

Progress:

<form name="edituserform" method="post" action="<?php echo $PHP_SELF;?>">
<select name="editinguser">
<option value="0">Phone Not Recieved</option>
<option value="20">Phone Recieved</option>
<option value="40">Parts Recieved</option>
<option value="60">Repair Started</option>
<option value="80">Repair Finished</option>
<option value="100">Posted Back</option>
</select>
<input type="hidden" name="edituserid" id="edituserid" value="<?php echo "$varID"; ?>" />
<input type="submit" name="edituser" id="edituser" value="Edit" />
</form>
    <?php
    if(isset($_POST['edituser'])){

    $add = $_POST['edituser'];
    $varIDe = $_POST['edituserid'];
    $errorMessage = "Jesus Christ Benton, Choose a User!!";
    $query1 = mysql_query("UPDATE users SET progress = $add WHERE UserID = $varIDe");
    mysql_query($query1) or die("Cannot update");

echo $add;
echo $varIDe;

    }
    ?>

<?php
}
?>

I'm not sure if the variables are working or not, or if it's the way I've used the submit button before? Its got me a little stumped.

A: You're query should be
$query1 = mysql_query("UPDATE users SET progress = '$add' WHERE UserID = $varIDe");

Don't forget the quotes
and it would be best to change your
mysql_query($query1) or die("Cannot update");
to mysql_query($query1) or die("MySQL ERROR: ".mysql_error());
to get it to display errors
edit
Found a few errors
mysql_numrows should be mysql_num_rows
and major error
$query1 = mysql_query("UPDATE users SET progress = $add WHERE UserID = $varIDe");

is running a query, change it to
$query1 = "UPDATE users SET progress = '".$add."' WHERE UserID = '".$varIDe."'";

A: I think your getting the wrong variable
if(isset($_POST['edituser'])){
  $add = $_POST['edituser']; // this is a button

should be :
if(isset($_POST['editinguser'])){
  $add = $_POST['editinguser']; // this is a select list

But please read the following about SQL Injection

A: When something's going wrong, with respect to query, you better debugging, adding one: or die ( mysql_error ( ) ) ; and then the error message is displayed.

A: $query1 = mysql_query("UPDATE `users` SET `progress` = '".$add."' WHERE UserID = '".$varIDe."'");
if(mysql_query($query1))
{
//DO SOME ACTION
}
else
{
die(mysql_error());
}


text:
Q: How to exclude docker files from time machine backups I don't need back up of my docker files. How do i exclude them from time machine backups
I see people mentioning /Users/david/Library/Containers/com.docker.docker folder but that does not exists on my machine.

Docker engine version: 20.10.2 running on
Big Sur: 11.2

Update: Found the location
My virtual machine appears to be here. I added it to the list of folders to be excluded. However that folder is not shown in the Time Machine UI.

tmutil addexclusion  /Users/david/Library/Containers/com.docker.docker/

A: There is a preference in Docker for this.
See screenshot from Docker Desktop 4.0.1:

From this SE posting and this Docker forum posting I learned that you can run the following command to see what is being excluded from Time Machine:
sudo mdfind "com_apple_backup_excludeItem = 'com.apple.backupd'"

When I run that command in my own Mac I find the following 2 exclusions listed:
/Users/user/Library/Containers/com.docker.docker/Data/vms/0/data
/Users/user/Library/Containers/com.docker.docker

The second directory listed there doesn't exist on my Mac but the former one includes a 64GB docker.raw file.
I am on Macos 11.6 Big Sur.
Despite all this I do find anecdotally that when I am running Docker my Time Machine backups are larger than when I am not running Docker, which makes me wonder if there are other locations that ought to be excluded but are not.

A: I use the generic addexclusion clause of tmutil to make files not get backed up even if I move or copy them.
Open a Finder window to the files and a command line prompt (terminal.app is fine for this) and drag that file into the prompt after typing tmutil addexclusion and press enter. Here you can see me checking files on the desktop of a user named mike...
bmike@m1 ~ % tmutil isexcluded /Users/bmike/Desktop/Docker\ Files
[Included]    /System/Volumes/Data/Users/bmike/Desktop/Docker Files
bmike@m1 ~ % tmutil addexclusion /Users/bmike/Desktop/Docker\ Files
bmike@m1 ~ % tmutil isexcluded /Users/bmike/Desktop/Docker\ Files
[Excluded]    /System/Volumes/Data/Users/bmike/Desktop/Docker Files


text:
Q: Unable to use WriteProfileInt() in a C++ windows application I am writing a C++ application, and I want to write an integer value to the INI file so that I can retain it back each time when i run the application.
But I am not able to use WriteProfileInt() API in my program, whenever I use this it gives me below error:-
'WriteProfileInt': identifier not found
However GetProfileInt() works fine, Can anyone please suggest me what should I do?
I am using Visual Studio 2013.
This is a sample code which I am using:-
public ref class main_form : public System::Windows::Forms::Form

{
public:

   int i2c_addr;
   int temp;

   main_form(void)
   {

      InitializeComponent();
   }

   void InitializeComponent(void)
   {
          WriteProfileInt(_T("device"),_T("i2c_address"),8);
          temp = GetProfileInt(_T("device"),_T("i2c_address"),0);
          this->i2c_addr = temp;
   }
}

But it gives me error for WriteProfileInt(_T("device"),_T("i2c_address"),8);
Please help me to proceed further on this.

A: On the API level you need to do something like this:
char bf[50];
sprintf(bf,"%d", my_int_value);
WriteProfileString("MyApp", "MySection", bf);  // will write to the registry
WritePrivateProfileString("C:\\myprog\\myprog.ini", "MySection", bf); // will write to the ini file

Hope this helps

A: Your code is trying to set the clock back 21 years.  Back to Windows 3.11, the last version of Windows that still had the Win.ini configuration file.
That cannot work anymore.  The winapi still supports GetProfileInt() to emulate some common entries in a Win.ini file and keep legacy code running.  But WriteProfileInt() has been completely removed, there's no hope to pretend that the .ini file is still there and can possibly function correctly.  Backwards compatibility is pretty legendary in Windows but the buck stops somewhere.  You found out where.
System.ini and Win.ini have been functionally replaced by the registry.  You can use that instead, perhaps, the RegistryKey class provides access to the registry.  In .NET, application settings are the recommended alternative to still keep configuration file-based.  Not convenient from C++/CLI however, the IDE doesn't have the settings designer like other languages have.  Keeping configuation in an XML file is in general a decent alternative, use the classes in the System.Xml namespace.


text:
Q: How do I tell if a sample data is roughly normal? (Normal Probability Plots) I don't understand why this graph shows that the data set is roughly normal:

I can see that the points are evenly spread out below and above the line, but why does that make the data approximately normal?
I'm also having trouble understanding where this formula comes from which describes the area under the standard normal curve to the left of $f_i$: $f_i = \frac{i-0.375}{n+0.25}$ where $i$ is the index of the arranged sample data and $n$ is the number of observations. Answering either question is fine.

A: I'm guessing this is a normal probability plot, which is designed so that if a normally distributed dataset is plotted on it, it will appear as the solid diagonal line in your image. The particular dataset that is plotted on the graph above is close to the solid line, so it is approximately normal.

A: The data is roghly normal in that it falls around the line and within the confidence bands. However, there is some correlation in the errors about the line that suggests it may be heavy tailed (i.e., the S-pattern). At 19 points, there just isnt enough data to make this "significant", but I'd guess more data may show a heavy tailed distributon, but the normal wouldn't be too far off.
To get a feel for what normal probability plots should look like for actual normal data, simulate some data (of various sample sizes e.g., 5, 20, 50, 100 points) from a normal distribution and run this exact same plot on it using a statisical package. You'll see what they look like when you know the data are normal. This should help your intuition, as distribution fitting is very visual.
Also, this like will be helpful: http://www.itl.nist.gov/div898/handbook/eda/section3/normprpl.htm


text:
Q: How to burn iso image to DVD using dd command I was looking at the command to burn iso image to a dvd. But I couldnt get the name of the device. In the /dev/ I could see cdrom,cdrw,dvd,dvdrw. I am using debian.
When I gave the command, I got the following output
dd if=debian-6.0.7-i386-DVD-1.iso of=/dev/dvdrw
dd: opening `/dev/dvdrw': Read-only file system

A: I believe growisofs uses dd, so the original command could work.
My example uses a 22G image to bluray.
Here is the output of growisofs using the dry-run option:
growisofs -dry-run -speed=1 -Z /dev/sr0=/snd/BDSV_3E.iso

return:
Executing 'builtin_dd if=/snd/BDSV_3E.iso of=/dev/sr0 obs=32k seek=0'

You can experiment. I suggest using cheaper DVDs or CDs

A: You can't use dd this way (it might work for DVD-RAM though). What you are looking for is growisofs - (the main) part of dvd+rw-tools.
growisofs -Z /dev/dvdrw=image.iso

A: Using dd command you can not write DVD.
You can write DVD using growisofs command.
First you have to create ISO Using dd command like
dd if=/dev/dvd of=my_test.iso bs=2048

Then write DVD Using this command
growisofs -dvd-compat -Z /dev/dvd=my_test.iso


text:
Q: Change URL of "View Cart" button on WooCommerce Pages other than Cart and Checkout I am applying the below code to change the URL of "View Cart" button on the Shop page.
// Change View Cart Button URL from /cart to /checkout
add_filter( 'woocommerce_add_to_cart_redirect', 'cart_to_checkout' );

function cart_to_checkout( $url ) {
    return wc_get_checkout_url();
}

What is the filter that I need to use to achieve the same for "View Cart" button in the "Woocommerce error message" on the Single Product Page?
Woocommerce error message" appears something like this: "The maximum allowed quantity for 'Product X' is 3 (you currently have 3 in your cart). "View Cart"
So, I need to change the URL of the "View Cart" button in the above message.
And also, all the View Cart buttons must point to Checkout Page and not Cart Page.
Thanks!

A: As this notice is hard coded in WC_Cart add_to_cart() method (from line 1075 to 1083):
throw new Exception(
    sprintf(
        '%s %s',
        wc_get_cart_url(),
        __( 'View cart', 'woocommerce' ),
        /* translators: 1: quantity in stock 2: current quantity */
        sprintf( __( 'You cannot add that amount to the cart — we have %1$s in stock and you already have %2$s in your cart.', 'woocommerce' ), wc_format_stock_quantity_for_display( $product_data->get_stock_quantity(), $product_data ), wc_format_stock_quantity_for_display( $products_qty_in_cart[ $product_data->get_stock_managed_by_id() ], $product_data ) )
    )
);

The only way to change the url link is using woocommerce_get_cart_url filter hook located inside the function wc_get_cart_url() (used in this notice) as follow for single product pages only:
add_filter( 'woocommerce_get_cart_url', 'filter_get_cart_url' );
function filter_get_cart_url( $url ) {
    // Only on single product pages
    if( is_product() )
        $url = wc_get_checkout_url();

    return $url;
}

To change all url links that are using wc_get_cart_url() to checkout url, you will use instead:
add_filter( 'woocommerce_get_cart_url', 'wc_get_checkout_url' );

Addition: To make it work everywhere except on cart and checkout pages, use the following:
add_filter( 'woocommerce_get_cart_url', 'filter_get_cart_url' );
function filter_get_cart_url( $url ) {
    // Except on cart and checkout pages
    if( ! ( is_cart() || is_checkout() ) )
        $url = wc_get_checkout_url();

    return $url;
}

Code goes in functions.php file of your active child theme (or active theme). Tested and works.

Related: Change the "view cart" product overlay button on product loops in Woocommerce


text:
Q: Removing specific pattern from string in Python? I have a string such as

' This is a nice string with some size in inches at the end 25.6" '

Number before the double quotes might be float or integer of any length. I want to remove everything between a space and double quote sign. Right now I am trying to do something with .find() functions to get the index of double quote sign and the last space and then to remove each symbol between those indexes. Is there any smarter way to do so?

A: We can try using re.sub here:
input = ' This is a nice string with some size in inches at the end 25.6" '
output = re.sub(r'\s+\d+(?:\.\d+)"\s*$', '', input)
print(output)

This is a nice string with some size in inches at the end

The regex pattern \s+\d+(?:\.\d+)"\s*$ says to:
\s+       match one or more spaces
\d+       match one or more digits, followed by
(?:\.\d+) an optional decimal component
"         inches unit sign
\s*       possible trailing whitespace, until
$         the end of the string


text:
Q: TextBox validating, integer with symbol I want to limit the user only able to key in integer (not double) and with symbol "," in the textBox. I have try this code, but it always pop on the messagebox when i try to erase the wrong input.
if (!System.Text.RegularExpressions.Regex.IsMatch(textBox4.Text, @"^[0-9,-Key.Back]"))
{
    MessageBox.Show("This textbox accepts only alphabetical characters");
    //textBox4.Text.Remove(textBox4.Text.Length - 1);
    //textBox4.Clear();
}

Please help.

A: I guess you are running the code in the TextChanged event handler. The problem is with your regex. You say you need to allow digits and commas, but you are checking if there are digits, ,, some range between , and K and some letters (e, y, etc) with a literal dot at the beginning of the string.
I think you want to fix it like
if (!System.Text.RegularExpressions.Regex.IsMatch(textBox1.Text, @"^[0-9,]*$"))
{
    MessageBox.Show("Please enter only numbers and commas.");
}

The ^[0-9,]*$ regex returns true when the whole input contains digits and commas from start to end.
If you need to allow just whole numbers with , as a decimal separator, use
^\d+(?:,\d+)?$

If you want to allow whole integer numbers with , as a digit grouping (thousand separator) symbol, use
^\d{1,3}(?:,\d{3})*$

To process the Key.Back key you need to implement the behavior you want in the KeyDown/KeyPress event handler, see How can I determine if the Backspace has been pressed in the KeyPress event?.

A: Try this:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (!char.IsDigit(e.KeyChar) && e.KeyChar != ',' && e.KeyChar != (char)Keys.Back)
    {
        e.Handled = true;
        MessageBox.Show("Digits, commas and backspace only");
    }
}


text:
Q: How to extract years as an array from pandas df How can I extract years as an array from pandas df date-time object? When trying
years = ([employees['Hiring Date'].dt.year]), the "years" comes as a list.

A: This could not work for you since I might have misread your post but I would try:
years = df['hiring date'].values

And then:
years = np.array(years)

A: *

*Use pandas.Series.to_numpy
from datetime import datetime
import pandas as pd

# data
data = {'Hiring Date': pd.bdate_range(datetime(1971, 1, 1), freq='2m', periods=40).tolist()}

# dataframe
employees = pd.DataFrame(data)

# extract years
years = employees['Hiring Date'].dt.year.to_numpy()

print(years)
[1971 1971 1971 1971 1971 1971 1972 1972 1972 1972 1972 1972 1973 1973
 1973 1973 1973 1973 1974 1974 1974 1974 1974 1974 1975 1975 1975 1975
 1975 1975 1976 1976 1976 1976 1976 1976 1977 1977 1977 1977]

print(type(years))
<class 'numpy.ndarray'>

print(years.shape)
(40,)


text:
Q: Strange behavior of atomic_fetch_add regarding uint64 I have the following code:
#include "atomic"

std::atomic<uint64_t>bid_index(0);
uint64_t generate_bid_key(){
  return std::atomic_fetch_add(&bid_index,1);
}

I have the following error:
No matching function for call to 'atomic_fetch_add' candidate template ignored:
deduced conflicting types for parameter '_Tp' ('unsigned long long' vs. 'int')
candidate template ignored: deduced conflicting types for
parameter '_Tp' ('unsigned long long' vs. 'int')
candidate template ignored: could not match 'type-parameter-0-0 *' against
'unsigned long long' candidate template ignored: could not match 'type-parameter-0-0 *'
against 'unsigned long long'

Can anyone help?

A: std::atomic_fetch_add deduce the templated type of the operand from the 2nd parameter 1 (which is an int) and it does not match the atomic's templated type (which is an uint64_t). Make it a uint64_t and it'll be accepted.
return std::atomic_fetch_add(&bid_index,1ULL);

or
return std::atomic_fetch_add(&bid_index,(uint64_t)1);

You can also use the more direct fetch_add method of the atomic class which is probably easier.


text:
Q: SaveChanges on removed entity throws DuplicateKeyException I create an entity object and store it in the database. Then I create a second one with the same PrimaryKey value (from a timestamp and an id column), but different content. Adding this to the DbContext throws 'InvalidOperationException', so I catch that and do a context.Update(obj). Now the SaveChanges() throws a 'DbUpdateException', where the InnerException shows a 'DuplicateKeyException', but objects state is 'Modified'.
At this point, I try to delete the old record and store the new, but SaveChanges(true) already throws 'DbUpdateException->DuplicateKeyException' after context.Remove(obj).
I try to do this in a separate Transaction with two SaveChanges(true) calls, but the first failed.
Didn't find a solution in StackOverflow nor MS documentation.
Here some example 'lookalike'-code:
// Example Model-Class
public partial class MyEntity
{
    public DateTime Timestamp { get; set; } // this and ...
    public int id { get; set; }             // this is the PrimaryKey in DB and DbContext classes
    public String Data { get; set;}
}
:
:
// Do the work somewhere
MyEntity entity1 = CreateEntity(new DateTime(2020,1,1,0,0,0), 1, "Ape");
SaveMyStuff(entity1, false);

MyEntity entity2 = CreateEntity(new DateTime(2020,1,1,0,0,0), 1, "Ape");
try {
    SaveMyStuff(entity2. false);
}catch(InvalidOperationException iOpEx)
{ /* Expected this, so do nothing */ }

MyEntity entity3 = CreateEntity(new DateTime(2020,1,1,0,0,0), 1, "Monkey");
SaveMyStuff(entity3, true); // <-- FAIL
:
:

public void SaveMyStuff(MyEntity entity, bool Overwrite)
{
    MyDbContext context = serviceProvider.GetRequiredService<MyDbContext>(); // via AddDbContextPool()
    try {
        context.Add(entity);
    }catch (InvalidOperationException iOpEx)
    {
        if( Overwrite )
        {
            // If the context already know entity's primary keys, do a update instead
            context.Update(entity);
        }
        else
            throw iOpEx;
    }
    try {
        context.SaveChanges(true);
    }catch(Microsoft.EntityFrameworkCore.DbUpdateException dbUpdEx)
    {
        if( Overwrite )
        {
            using (TransactionScope scope = new TransactionScope())
            {
                context.Remove(entity);
                context.SaveChanges(true); // <-- throws DuplicateKeyException
                context.Add(entity);
                context.SaveChanges(true);
                scope.Complete();
            }
        }
        else
            throw dbUpdEx;
    }
}

Did I miss some patterns or HowTo's to do such stuff?


text:
Q: fun style cross-strike-out I want to cross out (strike out) words or letters in fun ways for poster-sized text for children.
ulem and cancel produce rather formal/sterile-looking cancellations, as do tikz-based combinations of diagonal or wavy lines.
Are there any existing packages that can produce something like these 'sexy' (?) strikeouts, and accurately place them over non-monospaced fonts?

Here is my MWE, and its formal result:

\documentclass[oneside,11pt]{article}
\usepackage[a4paper, margin=0.4in,landscape] {geometry}
\usepackage{fontspec,ulem}
\setmainfont{Gill Sans}[Scale=14,BoldFont={Gill Sans SemiBold}]
\pagestyle{empty}
\renewcommand{\ULthickness}{10pt}%
\newcommand{\poster}[1]{
\vspace*{\fill}
\hspace*{\fill}#1\hspace*{\fill}
\vspace*{\fill}}
\begin{document}
\poster{merr\sout{y}ily}
\end{document}

A:
Just overlaying an image with a transparent background

\documentclass[oneside,11pt]{article}
\usepackage[a4paper, margin=0.4in,landscape] {geometry}
\usepackage{lmodern,graphicx}

\def\xout#1{\sbox0{#1}\usebox0%
\raisebox{-\dp0}{\llap{\includegraphics[totalheight=\dimexpr\ht0+\dp0,width=\wd0]{crosstr.png}}}}

\pagestyle{empty}

\newcommand{\poster}[1]{%
\vspace*{\fill}
\hspace*{\fill}#1\hspace*{\fill}
\vspace*{\fill}}
\begin{document}\fontsize{2cm}{2.1cm}\sffamily
\poster{merr\xout{y}ily}
\end{document}


text:
Q: UTF-8 characters not displaying properly from JPEG IPTC data in PHP When reading the IPTC data from an image, UTF-8 accented characters are not displaying properly when reading them via PHP.
For example: é, ø and ü
With a header content-type set as UTF8, instead of the character, I get the question mark in a black diamond. �  If no content-type is set, then I get a dash character: —
The following is the code being used to read the IPTC block:
$file = '/path/to/image.jpg';
getimagesize($file, $info);
$iptc = iptcparse($info['APP13']);

I have also tried uploading the exact same image to a WordPress installation on the same server, and it properly strips the accented character and replaces it with it's basic latin equivalent. I don't mind if this is the end result, I would just like to read the characters properly.
Any ideas on how to get the complete and correct data from the image?

A: Answering a bit late, but since I had the same problem displaying special characters as č š ž (which appear in Slovenian alphabet) I may aswell answer for future reference.
Solution to this problem actually is not related to php, but to the IPTC data encoding. By default most software that can write IPTC data will store it in plain ASCII. At first I've used Adobe Bridge - which actually displays all special characters as it should when you start tagging your images - but once you want to parse that data in PHP you will actually not see special characters. (I would have to check again this part, but the main catch is that two different encodings happen - one that encodes IPTC data on the image and one that displays that data in a program that can handle IPTC data - or something along this lines).
To solve the problem I used a program called ExifTool which is an amazing piece of software and will let you manage almost any data on your image.
Than I used it to convert all IPTC encodings to UTF-8 - and from then on I just had to retag images that had corrupt characters (which Adobe Bridge correctly displays but obviously does not save in correct encoding).
The command to accomplish this on all images in a folder is:
exiftool -tagsfromfile @ -iptc:all -codedcharacterset=utf8

You may also want to download ExifTool GUI if you are not familiar working from cmd.
I haven't found any better program that could accomplish this same task faster.

A: to set charset to utf8, use this code:
$iptc = array(
  '1#090' => "\x1B%G" //utf8
);

change that part of code like this:
// Convert the IPTC tags into binary code
$data = '';

foreach($iptc as $tag => $string)
{
  $rec = substr($tag, 0,1);
  $tag = substr($tag, 2);
  $data .= iptc_make_tag($rec, $tag, $string);
}

// Embed the IPTC data
$content = iptcembed($data, $path);


text:
Q: Why is silicon used as PCBs? I know why silicon is used for ICs and transistors in general due to its doping features. But I don't know why we use silicon as a PCBs, all we need is to isolate pins from each other in a PCB, right? So, will any insulating material work? Such as wood?

A: PCB's are NOT made of silicon!
PCBs are made from coated paper (coated to make it somewhat fire resistant), this is the cheap option.
Better PCBs are made from epoxy coated fiberglass, a common material is FR4.
Reasons not to use silicon for PCBs:

*

*Silicon is only a good isolator when it is very pure (no contaminants). For making semiconductors extremely pure Silicon manufactured. This is expensive to make but not much of it is needed per transistor / IC so the total material cost per device is quite low.

*Silicon is very brittle it is simply unsuitable to make a strong PCB that can withstand some mechanical force.
Reasons not to use wood for PCBs:

*

*Wood is flammable

*Wood is not strong when it is thin.

*Wood can bend over time due to aging and moisture.
Coated paper and FR4 do not have the disadvantages mentioned above. Also, it is easy to coat them with copper to make the connections. It is easy to drill holes in the material. These materials are cheap.

A: After some research, silicon pcb does exists and there is an industry doing them.
As this publication shows
https://www.eejournal.com/article/20130723-siliconcirc/
"Silicon circuit boards (SiCBs) are similar to printed circuit boards (PCBs) but made with a silicon substrate rather than FR-4."
They allow pad pitch of 30-40 micron. Or 3 micron according to the second link.
The main purpose as advertised is ultra high density,for micro scale systems.
This company manufactures them http://www.sbmicrosystems.us/what/silicon-pcbs/
One can see the use, with specific miniaturized ICs into small devices as wearable glasses, health monitoring ring, or substrate interconnect for CPUs/cache memory, nano robotics...
It's a very specific use and they are not meant to replace Pcbs.

A: Never seen a PCB made from Silicon, for the reasons others have mentioned.  Or for wood for that matter.
Materials I have used in designs include FR-4, Polyimide, Duroid (PTFE), Megtron, and ceramics.
Silicon as a substrate material actually does make some technical sense in that if you attaching bare Si chips to the substrate (using flip chip or bump pad technology), the fact that the CTE of the substrate matches the CTE of the chips means that you are much less likely to have cracked interconnects.  But, except for some R&D activities, I've never seen that actually used in a product.
Would be interesting to hear anyone else's experience in this area.  Maybe I should just make this into a new question.


text:
Q: Using Auth0 to authenticate through custom scenario? I have an idea for a Minecraft plugin which will allow users to log into the website associated with the server without requiring registration, all they would require is their Minecraft username.
I'm trying to find the best way to get Auth0 to authenticate users through a custom passwordless strategy, instead of the default email or SMS which Auth0 provide.
The context which I'll be using this in is as follows:
Minecraft username is entered as their login on the site > Magic link is sent to their text box in-game through a custom plugin and listener > User clicks on the magic link and they are authenticated using Auth0 (JWT token for 30-ish days).
Does this sound possible? or is it wishful thinking.
I know I'll need a custom listener to look for requests from Auth0 and something to return the magic links to the user in-game through a java plugin.

A: I see no reason that it wouldn't be possible, but there are a few factors to take into consideration:

*

*Minecraft chat cannot be assumed private and direct. There are chat logs and plugins that can intercept your messages. Passwordless auth is like communicating a one-time-use password, so why would you send it via insecure means?

*If we assume it's secure, typically it's the responsibility of the user to store the JWTs. If this is a vanilla client, you have no method of storing data on the client, so in the end the server is managing JWTs, which kills the entire reason to use them. Otherwise, why not just have the listener add the player to, say, a cache that expires Players after 30 days of not being accessed?

Other than these two kinks that can be worked out, it sounds like a cool idea. Good luck with it!


text:
Q: OcotberCMS - "SQLSTATE[42S22]: Column not found: 1054 Unknown column 'users.application_id' I am getting this error message with relations but I can't find out what I need to do to stop this error.
I have an Application model with a controller and component.  In the backend I can add a new Application record.  But to view I get the error.
  "SQLSTATE[42S22]: Column not found: 1054 Unknown column 'users.application_id' in 'where clause' (SQL: select * from `users` where `users`.`deleted_at` is null and `users`.`application_id` = 1 and `users`.`application_id` is not null limit 1)" on line 662 of /srv/users/sssandwich/apps/website/public/vendor/laravel/framework/src/Illuminate/Database/Connection.php

I isolated the error to appear when I add this code in fields.yaml of
Acme\Models\Application\fields.yaml.
# ===================================
#  Form Field Definitions
# ===================================

fields:
    client:
        label: Client
        type: relation
        disabled: true
        select: concat(name, ' ', surname)
        span: left

In
Acme\Models\Application.php

I have the relations set up as
/**
     * @var array Relations
     */
    public $hasOne = [
    'client' => ['RainLab\User\Models\User', 'table' => 'users'],
    'cv' => ['Acme\Acme\Models\Cv']
    ];
    public $hasMany = [];
    public $belongsTo = [
    'owner' => ['Backend\Models\User']
    ];

Below is the database structure...
public function up()
{
    Schema::create('acme_acme_applications', function(Blueprint $table) {
        $table->engine = 'InnoDB';
        $table->increments('id');
        $table->string('jobs_id')->nullable()->index();
        $table->string('application_id')->nullable()->index();
        $table->string('owner_id')->nullable()->index();
        $table->string('user_id')->nullable()->index();
        $table->string('vacancy_id')->nullable()->index();
        $table->string('ref_no', 50)->nullable();
        $table->char('status_update')->nullable();
        $table->timestamps();
    });
}

I have grep'd 'application_id' and it only appears in the db structure.  The users table is the Rainlab User plugin, but I am not sure why it trying to find the application_id in that table.

A:  "SQLSTATE[42S22]: Column not found: 1054 Unknown column 'users.application_id'...

I think this error is self-explanatory the Application Model is assumed to have a application_id foreign key because you defined a One-To-One Relation ;
If the Application Has-One User then the User's table should include an application_id column :
 public $hasOne = [
    'client' => [
    'RainLab\User\Models\User',
    'table' => 'users',
    'key' => 'application_id', // the foreign key in User's table
    'otherKey' => 'id', // Model record id
        ],
    ];

and you should define the inverse relation in the User's Model, a User belongsTo
 public $belongsTo = [
    'application' => [
    'Acme\Models\Application',
    'table' => 'acme_acme_applications',
    'key' => 'application_id',
    'otherKey' => 'id',
        ],
    ];

If you don't want to directly edit the RainLab User's plugin ( changes will be lost during updates ), have a look here how it extends the plugin and adds multiple columns to the database .


text:
Q: I tried send photo to firebase with using python but i have got error i am getting this error:

AttributeError: module 'requests' has no attribute 'auth'

firebase=pyrebase.initialize_app(config)
storage=firebase.storage()
path_on_cloud="images/c1.png"
path_local="c1.png"
storage.child(path_on_cloud).put(path_local)


text:
Q: need jquery validation for phone and country Iam working on JQuery Validation..
Iam facing problems with Phone Validation and Iam not understanding how to add another validation as below:
Here is what Iam achieving for:
- telephone number in all UK formats (4 digit area code, a space, 7 digit local code), The 'telephone' number field (4 digit area code, a space, 7 digit local code)

- visitor location from a drop-down list which includes the items: South Yorkshire, Rest of England, Wales, Scotland, Northern Ireland, European Union, Rest of World, Other, and which includes an appropriate default,

please kindly check my code here: http://jsfiddle.net/B5sd8/18/

A: Why don't you use a Masked Input like this?  Look at the Demos, and I am pretty sure you can format your mask to suit whatever phone number you need in the world.

A: You may be interested in existing web services such as GeoNames that allow you to search for an address (or simply a country) for checking purpose.
I would highly recommend using jQuery validate rather than re-inventing the wheel
a quick google search for uk numbers with jquery validate turned this up
filters
that looks like this
jQuery.validator.addMethod('phoneUK', function(phone_number, element) {
  return this.optional(element) || phone_number.length > 9 &&
  phone_number.match(/^(\(?(0|\+44)[1-9]{1}\d{1,4}?\)?\s?\d{3,4}\s?\d{3,4})$/);
  }, 'Please specify a valid phone number'
);