text:
Q: Change name of an existing categorySource and then set as defaultCategory during runtime (Ent Lib 5) I have a value called appName, defined in the app config that stores the name of an application. The application writes logs to a database via a Database Trace Listener. What I am trying to do is have the application take it's appName value and set the defaultCategory to have that same value at runtime. I assume I also have to rename the existing category to appName's value as well. I don't want to affect anything other than the name of that category and the change to the defaultCategory (to the renamed one).
Here's the config section, TESTING is the value I want to change at runtime:
<loggingConfiguration name="" tracingEnabled="true" defaultCategory="TESTING">

...

<categorySources>

 ...

 <add switchValue="All" name="TESTING">
  <listeners>
    <add name="Database Trace Listener" />
  </listeners>
 </add>
</categorySources>

I've tried looking up a solution/example but to closest thing I found re-wrote the whole section and I'd rather avoid that.

A: Enterprise Library supports run-time programmatic configuration or design-time declarative configuration for a single application block.  But out of the box you can't really mix the two approaches easily for the same application block.
You mention one approach which is to modify the configuration and write it back.
Another approach would be to set all configuration programmatically at runtime.
An alternative which can work if you use an external configuration file (e.g. FileConfigurationSource in app.config/web.config that points to the actual Enterprise Library configuration) is to load the configuration information and then modify it in memory.  The reason to use an external configuration file is to avoid a readonly configuration exception when trying to modify the configuration information.
That last approach is laid out in the article Enterprise Library Programmatic Configuration.


text:
Q: Which content type should use for all types of files to download file in asp.net? I have functionality to download file in asp.net. I have bytes, filename and size. I have tried by following way but whenever I open file, it doesn't open correctly. If it's jpg or png file, it doesn't display picture.
Here is my code on button click:
byte[] bytes = Encoding.ASCII.GetBytes(getStringFromServer());
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/octet-stream";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();

I have read somewhere that I need to specify ContentType. But in my case, file can be of any type.
Can anybody please guide me appropriate way?

A: i had same problem and solve it with very simple way
usually your file name has file type So i use this code:
 string fileType = fileName.Substring(fileName.LastIndexOf(".") + 1);
        if (FileFetchManager.IMAGE_TYPES.Contains(fileType, StringComparison.OrdinalIgnoreCase, true))
            HttpContext.Current.Response.ContentType = "image/" + FileFetchManager.ConvertFileExtensionToImageFormat(fileType).ToString();
        else
            HttpContext.Current.Response.ContentType = "application/" + fileType;

this is my FileFetchManager class:
  public class FileFetchManager
{
    public const string DEFAULT_FILE_TYPE = "txt";

    public static readonly string[] IMAGE_TYPES = { "bmp", "jpg", "jpeg", "png", "gif", "tiff", "tif" };

    public static string GetFileFetchUrl(string TableName, string FieldName, string FileNameFieldName, string PrimaryKeyValue)
    {
        return GetFileFetchUrl(TableName, FieldName, FileNameFieldName, PrimaryKeyValue, null);
    }

    public static string GetFileFetchUrl(string TableName, string FieldName, string FileNameFieldName, string PrimaryKeyValue, int? thumbnailImageSize)
    {
        return QueryStringCoder.CodeUrl("~/UserControl/JcoDataGrid/DBFileFetch.aspx?t=" + TableName + "&f=" + FieldName + "&fnf=" + FileNameFieldName + "&i=" + PrimaryKeyValue + (thumbnailImageSize == null ? "" : "&s=" + thumbnailImageSize));
    }

    public static string GetFileFetchUrl(string fileBytesSessionName, string fileName)
    {
        return GetFileFetchUrl(fileBytesSessionName, fileName, null);
    }

    public static string GetFileFetchUrl(string fileBytesSessionName, string fileName, int? thumbnailImageSize)
    {
        return QueryStringCoder.CodeUrl("~/UserControl/JcoDataGrid/MemoryFileFetch.aspx?sn=" + fileBytesSessionName + "&fn=" + fileName + (thumbnailImageSize == null ? "" : "&s=" + thumbnailImageSize));
    }

    public static string GetFileType(string fileName)
    {
        if (fileName.IsNullOrWhiteSpace())
            return DEFAULT_FILE_TYPE;
        return fileName.Substring(fileName.IndexOf(".") + 1);
    }

    public static bool IsImage(string fileName)
    {
        string fileType = fileName.Substring(fileName.LastIndexOf(".") + 1);
        bool isImage = FileFetchManager.IMAGE_TYPES.Contains(fileType, StringComparison.OrdinalIgnoreCase, true);
        return isImage;
    }

    public static byte[] GetThumbnailImage(string fileName, byte[] imageBytes, int size)
    {
        if (size <= 0)
            throw new Exception("ErrorCode : 1390/10/23-22:04 : " + QueryStringCoder.Code("اندازه درخواستي جهت تامبنيل تصوير(" + size + ") مجاز نمي باشد!"));
        ImageFormat imageType = ConvertFileExtensionToImageFormat(GetFileType(fileName));
        MemoryStream ms = new MemoryStream(imageBytes);
        ms.Position = 0;
        System.Drawing.Image img = System.Drawing.Image.FromStream(ms);
        int width;
        int height;
        if (img.Height > img.Width)
        {
            height = size.ToInt();
            width = img.Width * size.ToInt() / img.Height;
        }
        else //if (img.height <= img.width)
        {
            width = size.ToInt();
            height = img.Height * size.ToInt() / img.Width;
        }
        if (imageType == ImageFormat.Png || imageType == ImageFormat.Gif)
        {
            System.Drawing.Image.GetThumbnailImageAbort myCallback = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
            img = img.GetThumbnailImage(width, height, myCallback, IntPtr.Zero);
            imageType = ImageFormat.Png;
        }
        else
            img = ImageResizer.ConstrainProportions(img, height, Dimensions.Height);
        MemoryStream thumbnailImageStream = new MemoryStream();
        thumbnailImageStream.Position = 0;
        img.Save(thumbnailImageStream, imageType);
        return thumbnailImageStream.ToArray();
    }

    public static bool ThumbnailCallback()
    {
        return false;
    }

    public static ImageFormat ConvertFileExtensionToImageFormat(string fileExtension)
    {
        switch (fileExtension.ToLower())
        {
            case "jpeg":
            case "jpg":
                return ImageFormat.Jpeg;
            case "bitmap":
            case "bmp":
                return ImageFormat.Bmp;
            case "gif":
                return ImageFormat.Gif;
            case "icon":
            case "ico":
                return ImageFormat.Icon;
            case "png":
                return ImageFormat.Png;
            case "tiff":
            case "tif":
                return ImageFormat.Tiff;
            default:
                throw new NotImplementedException();
            //break;
        }
    }

    public static void SetResposeContentType(string fileName)
    {
        string fileType = fileName.Substring(fileName.LastIndexOf(".") + 1);
        if (FileFetchManager.IMAGE_TYPES.Contains(fileType, StringComparison.OrdinalIgnoreCase, true))
            HttpContext.Current.Response.ContentType = "image/" + FileFetchManager.ConvertFileExtensionToImageFormat(fileType).ToString();
        else
            HttpContext.Current.Response.ContentType = "application/" + fileType;
    }
}

i hope it's useful for you

A: The purpose of the content type is to allow the user agent (UA) to determine the type of the downloaded resource. Without a content type, the downloaded content is just naked data which could be anything.
It might be possible in some cases to infer the content type, but that is highly dependent on context. If the content is an image, the UA could infer the image type, if the content is text, it can check for a byte order mark etc. But since the data can be just about anything, it is impossible for the UA to do such an inferrence.
You have specified the content type application/octet-stream. That means you are telling the UA that the content is binary data. And that's how the UA is treating it. If you want the data to be recognized as an image, you need to specify the correct content type; application/octet-stream will not be enough.
When you store data that can be of any type, it is absolutely necessary for you to store the MIME type with the data. If you read the data from disc, you might be able to inder the content type from the file extension, but your server needs to do that, because the UA can't.

redpajama_set_name: RedPajamaStackExchange


text:
Q: dispose in flutter bloc On the code below,
profileBloc is initialized in EditProfileScreenState's didChangeDependencies() method.
Should we be calling dispose method on EditProfileScreenState class to dispose the profileBloc ?
If so , how should the profileBloc method be disposed as ProfileBloc class extends Bloc class which doesn't have dispose method?
class Profile extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (BuildContext context) => ProfileBloc(AuthRepo()),
      child: ProfileScreen(),
    );
  }
}

class ProfileScreen extends StatefulWidget {

  @override
  EditProfileScreenState createState() => EditProfileScreenState();
}

class EditProfileScreenState extends State<ProfileScreen> {

  ProfileBloc profileBloc;

  @override
  void didChangeDependencies() {
    profileBloc = BlocProvider.of<ProfileBloc>(context);
    super.didChangeDependencies();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    //profileBloc.dispose() cannot call as ProfileBloc class doesn't have dispose method
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: BlocConsumer<ProfileBloc, ProfileState>(
        listener: (context, state) {
        },
        builder: (BuildContext context,ProfileState state) {
          return RaisedButton(onPressed: ()=>profileBloc.add(SaveProfile("name","email")));
        }
      ));
  }
}

class ProfileBloc extends Bloc<ProfileEvent, ProfileState> {

  AuthRepo authRepo;

  ProfileBloc(this.authRepo) : super(ProfileSaved());

  @override
  Stream<ProfileState> mapEventToState(ProfileEvent event) async* {
    if (event is SaveProfile) {
      //Actions
    }
  }
}

A: While I was searching, I found the solution.
We don't need to initialize the profileBloc in didChangeDependencies().
We can access the add method directly from the BlocProvider using:
BlocProvider.of<ProfileBloc>(context).add(ProfileSaved())

We can remove following section from EditProfileScreenState class.
ProfileBloc profileBloc;

  @override
  void didChangeDependencies() {
    profileBloc = BlocProvider.of<ProfileBloc>(context);
    super.didChangeDependencies();
  }

Moreover,
In ProfileBloc class we can use close method in case we need to cancel any streams.
@override
  Future<void> close() {
    //cancel streams
    super.close();
  }


text:
Q: Bash script: Conditionally delete older files while keeping latest copies Note: Though there's an answer from jeff-schaller, it depends on zsh; so I would like to get an answer based on Bash.
I like to create a Bash script to conditionally delete older files from a backup directory.
There are 2 conditions for 2 distinct file backups:
1, Keep the latest copy of Edge_Profile_*.tgz, and delete rest of Edge_Profile_*.tgz only if they are older than 5 days.
2, Keep the latest copy of Firefox_Profile_*.tgz, and delete rest of Firefox_Profile_*.tgz, doesn't matter how old are they.
Here's how I have modify this AskUbuntu answer: https://askubuntu.com/a/933098/928088
Script:
#!/bin/bash

LOG_FILE="/home/admn/Cleanup.log"
TEMP_LOG="/tmp/Temp_Cleanup.log"

mv $LOG_FILE $TEMP_LOG

{

cd /home/admn/Downloads/Test;

echo "Cleanup log:" `date`

find /home/admn/Downloads/Test/Edge_Profile_*.tgz -type f \( -mtime +5 -printf 'Y\t' -o -printf 'N\t' \) -printf '%A@\t%p\0' |
    sort -zk2,2 | head -zn -1 | while read -r -d '' flag _ file; do \
        case "$flag" in
            'Y') echo rm "$file"
               ;;
            *) echo "skipping $file (too new)"
               ;;
        esac;
done

echo

find /home/admn/Downloads/Test/Firefox_Profile_*.tgz -type f \( -printf 'Y\t' -o -printf 'N\t' \) -printf '%A@\t%p\0' |
    sort -zk2,2 | head -zn -1 | while read -r -d '' flag _ file; do \
        case "$flag" in
            'Y') echo rm "$file"
               ;;
            *) echo "skipping $file (too new)"
               ;;
        esac
done

} &>> $LOG_FILE

cat $TEMP_LOG >>$LOG_FILE

exit;

Output in the logfile with echo:
/usr/local/scripts/cleanup.sh

rm /home/admn/Downloads/Test/Edge_Profile_Jul_06_2021_00-35.tgz
rm /home/admn/Downloads/Test/Edge_Profile_Jul_07_2021_00-35.tgz
....
skipping /home/admn/Downloads/Test/Edge_Profile_Jul_12_2021_00-35.tgz (too new)
skipping /home/admn/Downloads/Test/Edge_Profile_Jul_13_2021_00-35.tgz (too new)
....

rm /home/admn/Downloads/Test/Firefox_Profile_Jul_01_2021_00-35.tgz
rm /home/admn/Downloads/Test/Firefox_Profile_Jul_02_2021_00-35.tgz
....

Output in the logfile while actually running the script, without echo:
/home/admn/Downloads/cleanup.sh: line 24: skipping /home/admn/Downloads/Test/Edge_Profile_Jul_12_2021_00-35.tgz (too new): No such file or directory
/home/admn/Downloads/cleanup.sh: line 24: skipping /home/admn/Downloads/Test/Edge_Profile_Jul_13_2021_00-35.tgz (too new): No such file or directory
....

Total files in the directory: 20 files
1, Edge_Profile_*.tgz: From July 06 to July 17: 12 files
2, Firefox_Profile_*.tgz: From July 01 to July 08: 8 files
The issues:
(1) I think the script is kind of working but I'm not sure as I've modified most part without knowing what's going on.
(2) Output to logfile:
I would prefer the exact same output in the logfile that I get with echo, except just the filenames (not with full path), like:
rm Edge_Profile_Jul_11_2021_00-35.tgz

skipping Edge_Profile_Jul_12_2021_00-35.tgz (too new)

OS: Ubuntu MATE 21.04
Thanks a lot.

A: Manipulating files based on their modification times is much easier in a shell that lets you access them directly. zsh is one such shell. Simply sudo apt install zsh to install it. Since your files appear to be in one directory, this answer is non-recursive. Demonstrating the simpler case first:

*

*To keep the latest copy of Firefox_Profile_*.tgz and delete rest of them no matter how old they are:
echo would rm -v -- Firefox_Profile_*.tgz(.om[2,-1])

Remove the echo would  portion if it looks correct. This uses a glob (wildcard) qualifier inside the parenthesis to do three things:

*

*select only plain files (not directories or sockets or etc) with .

*order (sort) the files by their modification time, newest to oldest, with om

*select a slice of the resulting list starting from the second element to the end -- skipping the first (newest) file, with [2,-1]
If there are no matching files, zsh will stop and complain with "zsh: no matches found", and will not execute the rm.

*To keep the latest copy of Edge_Profile_*.tgz and delete the rest of them only if they are older than 5 days, first we grab the latest one:
newest=(Edge_Profile_*.tgz(.om[1]))

... and then we get the ones that are older than five days:
older=(Edge_Profile_*.tgz(.m+5))

The new part here is the +5 on the m modifier. That selects files that are older than 5 days. After that, we make sure the newest one isn't in the list to remove:
remove=("${(@)older:|newest}")

The new part here is the array subtraction symbol :|; it is documented in the Parameter Expansion section of the zsh manual. It selects the elements of "older" that are not in "newest". Finally, we remove that list of files:
echo would rm -v -- "${remove[@]}"


text:
Q: Using a group by or something similar using Splunk rex If we have data like this in the splunk logs -
 DepId EmpName
 100    Jon
 100    Mike
 100    Tony
 200    Mary
 200    Jim

Is there a way to display the records with only one line for the repeating DepIds.
So for example,something like below"
DepId   EmpName
100     Jon
        Mike
        Tony
200     Mary
        Jim.

A: Once you have the DepId and EmpName fields extracted, grouping them is done using the stats command.
| stats values(EmpName) as Names by DepId

Let us know if you need help extracting the fields.  Perhaps that's why "Splunk rex" is in the title?


text:
Q: Android accessory mode with multiple peripherals Android allows the development of USB accessories using USB Host mode and USB Accessory mode. If I connect a peripheral using accessory mode, would that make the phone unable to connect to other peripherals or to a desktop computer until the aforementioned HW is unplugged?
Usually there is only one USB port on the phone, but please assume the use of a hub.

A: Connecting a peripheral in USB Accessory mode would prevent you from using any other accessory at the same time, and no, a hub will not help.
This is because in Accessory mode, the peripheral is the USB host (while the phone is a USB device), and a USB bus can only have one host.  Therefore the Accessory mode restricts you to one accessory at a time.
If instead you used the USB Host APIs to make a (capable) phone the USB host, then there is some possibility that you might be able to use multiple USB device peripherals downstream of a hub - at least, the bus topology supports it, though I don't know for an absolute fact that the Android stack will.


text:
Q: Authentication using firebase Implement a single page called 'home' that needs authentication to be accessed. Use firebase authentication to implement auth. Add a profile management page(update name and profille picture), login, logout and forgot password. Would be nice if you add a Dockerfile to it for deployment. Use Nextjs for this
i have triedd creating the pages but now firebase is the problem


text:
Q: SQL Double/Triple the value with SUM and LEFT JOIN ACCESS 2007 I am getting my result doubled or triple or even x4, x5 depends how many rows I have in the table ONHAND, it returns like x2 or x4 or x4 from the correct value, actually the table ONHAND has 2 OR MORE rows* because there is a field called "Location" so those 2+ rows of the same subitem are located in different locations, so if I use the aggregate function **SUM() with this query it returns the wrong total, the Material requirement should be x1 of SUBITEM, instead x2 SUBITEM (x2 rows of SUBITEM in 2 different "Location" but in the same Warehouse in table ONHAND)... This sub-queries is what I have tried until now, but still getting double/triple total of the real values, and I need to use the table ONHAND because there is the Warehouse number.
this is what I am getting (multiplied by x3.)
subitem subitemDescription  fecha   TOTAL   Linea   Arearesponsable Areauso PlannerName ItemType    Surtimiento WH
01-0012 ADAPTOR,1/4 BARB X DOLE 30/08/2016  198             Nevarez, Vianey-Tube Bending    MFG     085

And this should be the correct TOTAL result
SUBITEM SUBITEM DESCRIPTION FECHA   TOTAL   7AM 8AM 9AM 10AM    11AM    12PM    1PM 2PM 3PM 4PM 5PM PLANNER NAME    ITEMTYPE
01-0012 ADAPTOR,1/4 BARB X DOLE 30/08/2016  66  66  0   0   0   0   0   0   0   0   0   0   Nevarez, Vianey-Tube Bending    MFG

    SELECT subquery1.subitem
    ,subquery1.subitemDescription
    ,subquery1.fecha
    ,subquery1.TOTAL
    ,subquery1.Linea
    ,subquery1.Arearesponsable
    ,subquery1.Areauso
    ,subquery1.PlannerName
    ,subquery1.ItemType
    ,subquery1.Surtimiento
    ,subquery1.WH
FROM (
    SELECT b.SUBITEM AS subitem
        ,b.[SUBITEM DESCRIPTION] AS subitemDescription
        ,p.FECHA AS fecha
        ,Sum(p.CANTIDAD * b.[BUILD REQ]) AS TOTAL
        ,pf.Linea AS Linea
        ,pf.Arearesponsable AS Arearesponsable
        ,pf.[Area de Uso] AS AreaUso
        ,b.[PLANNER NAME] AS PlannerName
        ,b.ITEMTYPE AS ItemType
        ,pf.SurtimientoKitKBHeijunka AS Surtimiento
        ,First(oh.Warehouse) AS WH
    FROM (
        (
            (
                PROGRAMA AS p LEFT JOIN TB_BOM AS b ON p.ITEM = b.BOM
                ) LEFT JOIN TB_PFEP AS pf ON b.SUBITEM = pf.[Numero de Parte]
            ) LEFT JOIN TB_KB AS kb ON pf.[Numero de Parte] = kb.[Item number]
        )
    LEFT JOIN TB_ONHAND AS oh ON b.SUBITEM = oh.[Item number]
    GROUP BY b.subitem
        ,b.[SUBITEM DESCRIPTION]
        ,p.FECHA
        ,pf.Linea
        ,pf.Arearesponsable
        ,pf.[Area de Uso]
        ,b.[PLANNER NAME]
        ,b.ITEMTYPE
        ,pf.SurtimientoKitKBHeijunka
        ,oh.Warehouse
    ) AS subquery1
WHERE (subquery1.fecha = [Buscar requerimento de material de la fecha: (mm/dd/aaaa)])
    AND (subquery1.WH = "085")
GROUP BY subquery1.subitem
    ,subquery1.subitemDescription
    ,subquery1.fecha
    ,subquery1.TOTAL
    ,subquery1.Linea
    ,subquery1.Arearesponsable
    ,subquery1.Areauso
    ,subquery1.PlannerName
    ,subquery1.ItemType
    ,subquery1.Surtimiento
    ,subquery1.WH;


text:
Q: sendmail: OpenSSL::SSL::SSLError: hostname was not match I have a vps with ubuntu 10.04. i'm tring to install a rails 3 application
If i try to test the sendmail command from terminal it works.
In my application,for the mail, i have inserted in application.rb file:
config.action_mailer.delivery_method = :sendmail
    config.action_mailer.sendmail_settings = {
        :location       => '/usr/sbin/sendmail',
        :arguments      => '-i -t'
    }

But if i try to send an email with rails i receive this error:
OpenSSL::SSL::SSLError: hostname was not match with the server certificate
    from /opt/ruby/lib/ruby/1.8/openssl/ssl-internal.rb:123:in `post_connection_check'

How can i do?
thanks

A: Maybe you need
:openssl_verify_mode  => 'none'

per Rails 3 actionmail OpenSSL::SSL::SSLError

A: just add to your enviroment.rb
module OpenSSL
  module SSL
    remove_const :VERIFY_PEER
  end
end
OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE


text:
Q: Confused about android clickable, focusable true-false and their work I have created a grid view follow this link
Android - Gridview with Custom BaseAdapter, get clicked View at position
It works fine. But I am confused at these two line in cell.xml
android:clickable="false"
android:focusable="false"

It is false but it is working when I click and it is not working when I turn it o true. So I am confused and I have some questions –
•   Why they are needed? When we generally create button we don't define these two attribute. But I when create a button for grid view cell why it is needed?
•   Why they work in reverse way?
•   Is there any way to avoid these two line?

cell.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <Button
        android:id="@+id/grid_item"
        android:layout_gravity="center"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="05"
        android:textSize="20sp"
        android:clickable="false"
        android:focusable="false"/>
    </Button>

</LinearLayout>

MainActivity.java
public class MainActivity extends Activity {

    private TextView text;
    private GridView gridView;
    private final String[] items = new String[]{"A", "B", "C", "D", "E", "F", "G", "H", "I", "J",
            "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};

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

        text = (TextView) findViewById(R.id.feedback);

        gridView = (GridView) this.findViewById(R.id.myGridView);
        CustomGridAdapter gridAdapter = new CustomGridAdapter(MainActivity.this, items);
        gridView.setAdapter(gridAdapter);
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                text.setText((String) (gridView.getItemAtPosition(position)));
                Log.i("ITEM_CLICKED", "" + (String) (gridView.getItemAtPosition(position)));
            }
        });

    }
}

CustomGridAdapter.xml
public class CustomGridAdapter extends BaseAdapter {

    private Context context;
    private String[] items;
    LayoutInflater inflater;

    public CustomGridAdapter(Context context, String[] items) {
        this.context = context;
        this.items = items;
        inflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    public View getView(int position, View convertView, ViewGroup parent) {

        if (convertView == null) {
            convertView = inflater.inflate(R.layout.cell, null);
        }
        Button button = (Button) convertView.findViewById(R.id.grid_item);
        button.setText(items[position]);

        return convertView;
    }

    @Override
    public int getCount() {
        return items.length;
    }

    @Override
    public Object getItem(int position) {
        return items[position];
    }

    @Override
    public long getItemId(int position) {
        return position;
    }
}

A: In most case the view for each cell doesn't have anything that could consume the click event. So when you click on a row, the onItemClickListener will be called by the GridView (or Listview).
But here there is a Button which is clickable by default. The thing is that a view inside a GridView can capture the click event and prevent the propagation to the gridview onItemClick event.
So to avoid the button to keep the event, you can say that it should not be clickable, with the attribute clickable.
Having clickable elements in a cell can be used to have multiple clickable area for each row.


text:
Q: How to configure active directory in windows 7? I just installed Remote Server Administrative Tools (RSAT) on windows 7, and turned features on as mentioned in the installation guide. Now the Administrative Tools have been installed and successfully listed in the All Programs list of start menu.
I want to set up a local network. I want to create users/passwords, and give them access to shared drives with permissions, etc.
My questions is:
How do I configure the Active Directory in windows 7 for the first time?
Edit 1
If Active Directory is not for windows 7, why has Microsoft provided RSAT for windows 7? (https://www.microsoft.com/en-us/download/details.aspx?id=7887)

A: As its name says, they are intenteded for a Remote Server Administration, so you need a Windows Server (it can be a VM) to create an Active Directory.
It's like you just installed the steering wheel but not the car...


text:
Q: Not showing the form post selection from drop down List I have task to automate filling of a web form. I am able open the form and able to select option from drop down and able to fill the form. Drop down have multiple options and show form according to the selection in the drop down. I able to select option from drop down through VBA coding but form is not expanding. Although It is get expanded through selection through mouse from drop down.
I have written the below code:
Sub FilltheForm1()

Dim IE As SHDocVw.InternetExplorer
Dim IE2 As SHDocVw.InternetExplorer

Set IE = New InternetExplorer
Set IE2 = New InternetExplorer

IE.Visible = True

IE.navigate "My URL"

Do While IE.readyState <> READYSTATE_COMPLETE
Loop

Dim Doc As MSHTML.HTMLDocument

Set Doc = IE.document

    Doc.getElementsByTagName("select").Item("userType").Value = "SERVICE_PROVIDER"

    Doc.getElementsByTagName("Input").Item("firstName").Value = "A"
    Doc.getElementsByTagName("Input").Item("middleInitial").Value = "A"
    Doc.getElementsByTagName("Input").Item("lastName").Value = "A"
    Doc.getElementsByTagName("select").Item("company").Value = "HCL"
    Doc.getElementsByTagName("Input").Item("companyEmail").Value = "A"
    Doc.getElementsByTagName("Input").Item("address").Value = "A"
    Doc.getElementsByTagName("Input").Item("city").Value = "A"
    Doc.getElementsByTagName("Input").Item("stateProvince").Value = "A"
    Doc.getElementsByTagName("Input").Item("zipPostalCode").Value = "A"
    Doc.getElementsByTagName("select").Item("country").Value = "INDIA"

    Doc.getElementsByTagName("Input").Item("phone").Value = "A"
    Doc.getElementsByTagName("textarea").Item("reasonForRequestingAccess").Value = "A"

End Sub

HTML Code of web Form:

User Type:*

        <select name='userType' class="selectDropDown" onChange=refreshPage()>
    <option value= 'PLEASE SELECT USER TYPE' selected ="selected">

A: You may need to Fire the OnChange event to mimic user interaction.
ie.document.querySelector("[name='userType']").FireEvent "onchange"


text:
Q: probability with exponential distribution there is a barber shop with two waiting chair and one barber.suggest that,when a customer comes in,and two waiting chair are full,he goes to another barber shop.
The time between entering of two customers,is an exponential random variable with average=a.
the need time for working on each customer,is an exponential random variable with average=b.
when the barber shop is empty,barber goes out from shop,for rest and after a period  of time that is an exponential random variable with average=c,he comes back to shop.
what percentage of customers that arrive, do lose ,because two waiting chairs are full?


text:
Q: Jquery load page with chitika ad , breaks site I have a header.php file that is included on every single page of my website and what i wanted is to load another php file that included my ad code for my website so I did and for somereason it will load it then redirect me to a blank page with just the ad on it ? please tell me if there is something wrong with my code thank you! here is a link to my website as well, as soon as it loads it redirects you... http://www.quickdailylaugh.com
This is the code to load it into the div.

This is the code on the ads.php file

right ad

A: By using the function document.write you are wiping out and replacing the HTML of your page. Instead, use the JS function .append or .innerHTML to add content to the existing div contentforads.


text:
Q: show progress percentage on progress bar I have some HTML file with css and javascript, it shows progress bar depending on project start date, end date and current date, it works fine but I need that progress percentage to show into the bar.
there is my file content:

  <meta http-equiv="content-type" content="text/html; charset=UTF-8">

 <link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">

  <title>Date to Percentage Progress</title>

A: Since you already using jquery. I would suggest to use jQueryUI progressbar UI widget and refer this example from the official jQueryUI website.
https://jqueryui.com/progressbar/#download
I hope this helps.


text:
Q: Github pages: How to extend base layout? In my github pages directory, I have a folder called _layout in which I have a template file called base.html.
It contains nothing more than:

Test 1

{{ content }}

Test 2

In each of my markdown pages (test.md), at the top of the file I have the following:
---
title: TEST PAGE
layout: base
---

Test Page Content

However, when I go to serve this website and I go to test.html, all that appears is the contents of the test page - it does not place itself in the layout defined by base.html.. what am I doing wrong? Thanks!

A: The folder should be called _layouts, with an s.


text:
Q: scrapy throw a send_catch_log_deferred exception on PyPy when I use scrapy shell on PyPy ,it's throw some Execption ,so what's this error?
This is error information
    % /usr/local/share/pypy/scrapy shell http://www.baidu.com
    zsh: correct 'shell' to 'shells' [nyae]? n
    2012-11-09 16:40:06+0800 [scrapy] INFO: Scrapy 0.16.1 started (bot: scrapybot)
    2012-11-09 16:40:06+0800 [scrapy] DEBUG: Enabled extensions: TelnetConsole, WebService, CloseSpider, CoreStats, SpiderState
    2012-11-09 16:40:06+0800 [scrapy] DEBUG: Enabled downloader middlewares: HttpAuthMiddleware, DownloadTimeoutMiddleware, UserAgentMiddleware, RetryMiddleware, DefaultHeadersMiddleware, RedirectMiddleware, CookiesMiddleware, HttpCompressionMiddleware, ChunkedTransferMiddleware, DownloaderStats
    2012-11-09 16:40:06+0800 [scrapy] DEBUG: Enabled spider middlewares: HttpErrorMiddleware, OffsiteMiddleware, RefererMiddleware, UrlLengthMiddleware, DepthMiddleware
    2012-11-09 16:40:06+0800 [scrapy] DEBUG: Enabled item pipelines:
    2012-11-09 16:40:06+0800 [scrapy] ERROR: Error caught on signal handler: <bound method instance.start_listening of <scrapy.telnet.TelnetConsole instance at 0x00000001063f0bc0>>
        Traceback (most recent call last):
          File "/usr/local/Cellar/pypy/1.9/site-packages/twisted/internet/defer.py", line 1045, in _inlineCallbacks
            result = g.send(result)
          File "/usr/local/Cellar/pypy/1.9/site-packages/scrapy/core/engine.py", line 75, in start
            yield self.signals.send_catch_log_deferred(signal=signals.engine_started)
          File "/usr/local/Cellar/pypy/1.9/site-packages/scrapy/signalmanager.py", line 23, in send_catch_log_deferred
            return signal.send_catch_log_deferred(*a, **kw)
          File "/usr/local/Cellar/pypy/1.9/site-packages/scrapy/utils/signal.py", line 53, in send_catch_log_deferred
            *arguments, **named)
        --- <exception caught here> ---
          File "/usr/local/Cellar/pypy/1.9/site-packages/twisted/internet/defer.py", line 134, in maybeDeferred
            result = f(*args, **kw)
          File "/usr/local/Cellar/pypy/1.9/site-packages/scrapy/xlib/pydispatch/robustapply.py", line 47, in robustApply
            return receiver(*arguments, **named)
        exceptions.TypeError: start_listening() got 2 unexpected keyword arguments

A: As far as I can see, scrapy uses lxml. Only very new lxml works (with also PyPy trunk, not PyPy 1.9), I would suggest trying it instead.


text:
Q: Collect cells in pandas df that are listed in another pandas df (with same index) Consider the following example (the two elements of interest are final_df and pivot_df. The rest of the code is just to construct these two df's):
import numpy
import pandas

numpy.random.seed(0)
input_df = pandas.concat([pandas.Series(numpy.round_(numpy.random.random_sample(10,), 2)),
                          pandas.Series(numpy.random.randint(0, 2, 10))], axis = 1)
input_df.columns = ['key', 'val']

pivot_df = input_df.pivot(columns = 'key', values = 'val')\
                   .fillna(method = 'pad')\
                   .cumsum()

index_df = pivot_df.notnull()\
                   .multiply(pivot_df.columns, axis = 1)\
                   .replace({0.0: numpy.nan})\
                   .values

final_df = numpy.delete(numpy.partition(index_df, 3, axis = 1),
                        numpy.s_[3:index_df.shape[1]], axis = 1)
final_df.sort(axis = 1)
final_df = pandas.DataFrame(final_df)

final_df contains as many rows as pivot_df. I want to use these two to construct a third df: bingo_df.
bingo_df should have the same dimensions as final_df. Then, the cells of bingo_df should contain:

*

*Whenever the entry (row = i, col = j) of  final_df is numpy.nan,
the entry (i,j) of bingo_df should be numpy.nan as well.

*Otherwise, [whenever the entry (i, j) of  final_df is not numpy.nan] the entry (i,j)  of bingo_df should be the value at cell [i, final_df[i, j].value] of pivot_df (in fact final_df[i, j].value is either the name of a column of pivot_df or numpy.nan)

Expected ouput:
so the first row of final_df is
0.55,  nan,  nan.
So I'm expecting the first row of bingo_df to be:
0.0, nan, nan
because the value in cell (row = 0, col = 0.55)  of pivot_df is 0
(and the two subsequent numpy.nan in the first row of final_df should also be numpy.nan in bingo_df)
so the second row of final_df is
0.55, 0.72,  nan
So I'm expecting the second row of bingo_df to be:
0.0, 1.0, nan
because the value in cell (row = 1, col = 0.55) of pivot_df is 0.0
and the value in cell (row = 1, col = 0.72) of pivot_df is 1.0

A: IIUC lookup
s=final_df.stack()
pd.Series(pivot_df.lookup(s.index.get_level_values(0),s),index=s.index).unstack()
Out[87]:
     0    1    2
0  0.0  NaN  NaN
1  0.0  1.0  NaN
2  0.0  1.0  2.0
3  0.0  0.0  2.0
4  0.0  0.0  0.0
5  0.0  0.0  0.0
6  0.0  1.0  0.0
7  0.0  2.0  0.0
8  0.0  3.0  0.0
9  0.0  0.0  4.0


text:
Q: python multi-threading slower than serial? I'm trying to figure out multi-threading programming in python. Here's the simple task with which I want to compare serial and parallel speeds.
import threading
import Queue
import time
import math

def sinFunc(offset, n):
  result = []
  for i in range(n):
    result.append(math.sin(offset + i * i))
  return result

def timeSerial(k, n):
  t1 = time.time()
  answers = []
  for i in range(k):
    answers.append(sinFunc(i, n))
  t2 = time.time()
  print "Serial time elapsed: %f" % (t2-t1)

class Worker(threading.Thread):

  def __init__(self, queue, name):
    self.__queue = queue
    threading.Thread.__init__(self)
    self.name = name

  def process(self, item):
    offset, n = item
    self.__queue.put(sinFunc(offset, n))
    self.__queue.task_done()
    self.__queue.task_done()

  def run(self):
    while 1:
        item = self.__queue.get()
        if item is None:
            self.__queue.task_done()
            break
        self.process(item)

def timeParallel(k, n, numThreads):
  t1 = time.time()
  queue = Queue.Queue(0)
  for i in range(k):
    queue.put((i, n))
  for i in range(numThreads):
    queue.put(None)
  for i in range(numThreads):
    Worker(queue, i).start()
  queue.join()
  t2 = time.time()
  print "Serial time elapsed: %f" % (t2-t1)

if __name__ == '__main__':

  n = 100000
  k = 100
  numThreads = 10

  timeSerial(k, n)
  timeParallel(k, n, numThreads)

#Serial time elapsed: 2.350883
#Serial time elapsed: 2.843030

Can someone explain to me what's going on? I'm used to C++, and a similar version of this using the  module sees the speed-up we would expect.

A: Python has a severe threading problem. Basically, adding threads to a Python application almost always fails to make it faster, and sometimes makes it slower.
This is due to the Global Interpreter Lock, or GIL.
Here's blog post about it that includes a talk on the subject.
One way to bypass this limitation is to use processes instead of threads; this is made easier by the multiprocessing module.

A: Other answers have referred to the issue of the GIL being the problem in cpython. But I felt there was a bit of missing information. This will cause you performance issues in situations where the code you are running in threads is CPU bound. In your case here, yes doing many calculations in threads is going to most likely result in dramatically degraded performance.
But, if you were doing something that was more IO bound, such as reading from many sockets in a network application, or calling out to subprocess, you can get performance increases from threads. A simple example for your code above would be to add a stupidly simple call out to the shell:
import os

def sinFunc(offset, n):
  result = []
  for i in xrange(n):
    result.append(math.sin(offset + i * i))
  os.system("echo 'could be a database query' >> /dev/null; sleep .1")
  return result

That call might have been something real like waiting on the filesystem. But you can see that in this example, threading will start to prove beneficial, as the GIL can be released when the thread is waiting on IO and other threads will continue to process. Even so, there is still a sweet spot for when more threads start to become negated by the overhead of creating them and synchronizing them.
For CPU bound code, you would make use of multiprocessing
From article: http://www.informit.com/articles/article.aspx?p=1850445&seqNum=9

...threading is more appropriate for I/O-bound applications (I/O releases
  the GIL, allowing for more concurrency)...

Similar question references about threads vs processes:
https://stackoverflow.com/a/1227204/496445
https://stackoverflow.com/a/990436/496445

A: Python libraries that are written in C can obtain/release the Global Interpreter Lock (GIL) at will.  Those that do not use Python objects can release the GIL so that other threads can get a look-in, however I believe that the math library uses Python Objects all the time, so effectively math.sin is serialised.  Since locking/unlocking is an overhead, it is not unusual for Python threads to be slower than processes.


text:
Q: Fadein at certain hour or time I wonder if this is possible? For a website concept I want to make something pop out or fade in at a certain hour according to the user's computer time. I have tried looking with no avail because I don't know what kind of function would control when an effect takes place.
Any ideas? Thank you.

A: If you know at what time to fadeIn (ahem) in, then simply calculate the delta between that time (that's supposedly in the future) and our time. Example:
var dateNow = new Date();

setTimeout(function() {
    doFadingInStuff();
}, dateWanted - dateNow);

A: If you get the current time and calculate the future time that you want the event to happen (thus you have an amount of elapsed time until your event should happen), you can use the setTimeout() function to schedule a function call at a precise time in the future.  From that function, you would do your animation.

A: Assuming you only want something to be visible during a certain hour (ie. fade in when it becomes that hour, fade out when it's no longer that hour), you could do this:
// element is assumed to be a jQuery object
var VISIBLE_HOUR=14; // 2:00 PM
function check() {
    var isHour=(new Date()).getUTCHours()==VISIBLE_HOUR;
    var isVisible=element.is(":visible");
    if(isHour!=isVisible) {
        element.fadeToggle(1000);
    }
}
// We probably don't want to check very frequently...
// You could make it more advanced by checking
// more frequently closer to the hour in which it would be visible.
setInterval(check, 30000);

A: Check out this fiddle
Your JS
var now = new Date().toString();

    $('#fadeMe').html(now).fadeIn(9000)

A: var eventHour = 16, // 4:00pm

    // get the current time as a Date
    now = new Date(),

    // turn your event time into a Date
    eventDate = new Date(now.getFullYear(),
                         now.getMonth(),
                         now.getDate(),
                         eventHour),

    // calculate how many MS until your event
    eventTimeMS = eventDate - now;
    dayInMS = 86400000,

    // your event
    myEvent = function() {
        alert('The time is now!');
    };

// adding 24 hours if already past event time today
eventTimeMS = eventTimeMS < 0 ? eventTimeMS + dayInMS : eventTimeMS;

// if currently the right hour, just invoke event
if (eventHour == now.getHours()) {
    myEvent();

// otherwise start a timer to invoke your event at the appropriate time
} else {
    setTimeout(myEvent, eventTimeMS);
}

A: I think you want to check the time of day for the client, then fade in or out. This would be done like so:
<html>
<head>
  <script type="text/javascript" src="jquery.js"></script>
  <script type="text/javascript">
    $(function(){
var sunriseHour = 1;
var sunsetHour = 19;

function checkForChange() {
    var nowDate = new Date();
    var nowHour = nowDate.getHours();
    if ((nowHour >= sunriseHour) && (nowHour < sunsetHour)) {
        if (sunPosition != 'up') {
            sunPosition = 'up';
            $('#theSun').fadeIn('slow');
        }
    } else {
        if (sunPosition != 'down') {
            sunPosition = 'down';
            $('#theSun').fadeOut('slow');
        }
    }
}

var nowDate = new Date();
var nowHour = nowDate.getHours();
if ((nowHour >= sunriseHour) && (nowHour < sunsetHour)) {
    $('#theSun').show();
    sunPosition = 'up';
} else {
    $('#theSun').hide();
    sunPosition = 'down';
}

setTimeout(checkForChange, 1000);

    });
  </script>
</head>

<body>
  <div id="theSun" style="background: yellow; width: 300px; height: 300px; display: none;">
  This box is the sun
  </div>
</body>
</html>


text:
Q: How I undo some changes in my workspace and get back to my last commit?
Possible Duplicate:
Git: Revert to previous commit status

I've tried some changes in my code but I messed up too many things (never work when you're tired and it's late) and I just want to go back to my last commit. I DIDN'T do git add or git commit and obviously if I do git pull everything is up to date.
I thought that git checkout was what I needed but it didn't worked.. any help?

A: DO NOT git reset -hard it is PERMANENT!
Please use
git stash -u

instead! If you have a piece of work in there that you zapped by accident, you can still get it back. This never gets pushed to your remote unless you choose to do so by making a branch out of it and pushing it up.
Also, you are on the right track that you can use git checkout to accomplish the same thing. The syntax is git checkout HEAD -- .. But it has the same problem as git reset --hard. Stick with stash and you will save losing your hair in the future.
Longer answer
The above solutions revert all your changes. However, you asked how to get rid of some of the changes. I'll add this for completeness.
To do this, you can
git add file1 file2 file3
git stash save --patch

You will now be prompted for what exactly you want to make dissappear... down to what ever level of granularity. So you can safely "reject" only a few changes to a single file if you choose to do so.

A: git reset --hard this will remove all of your untracked changes to last commit in repository.

A: git reset --hard will discard all of your work, but you probably want to do:
git stash save "A bunch of stuff that didn't work"

on the off chance that you want to recover some of the changes.

A: The answers mentioning reset --hard will do what you want (as well as some other things that you may or may not), but you were correct in thinking that checkout was the command you needed. The problem is that checkout does two different things, so you need to supply it with a path argument:

git checkout .

from the root of your repository will do you just fine.


text:
Q: Stash Repository/Project deletion failed and unable to add new users/groups in repositories I have installed stash 3.2 and added the evaluation license for testing purpose. i created a project and created the repository. I was testing the various functionalities by deleting a repository and project which failed. I tried to add group to repo which also failed. seeing the below in log
2014-08-20 11:09:09,490 INFO [http-bio-17993 exec-2] admin @L9VJK8x669x260x0 gnwktx 10.178.23.278 "GET /projects/MON/repos/testing/settings HTTP/1.1" c.a.s.i.w.a.RepositoryAdminController Failed to resolve default branch. Cause: refs/heads/master is set as the default branch, but this branch does not exist
2014-08-20 11:18:04,549 INFO [http-bio-17993-exec-4] admin @L9VJK8x678x404x0 gnwktx 10.178.23.278 "GET /projects/MON/repos/testing/settings HTTP/1.1" c.a.s.i.w.a.RepositoryAdminController Failed to resolve default branch. Cause: refs/heads/master is set as the default branch, but this branch does not exist
i get the below pop up while trying to add group(permission) for a particular repo
Something went wrong while trying to serve your request. Try reloading the page.
Help is much appreciated

A: You need to setup a default branch.Usualy master is the default branch but your repo does not have a master . You can do 2 things

*

*Create a master branch

*Set a default branch. You can do this in the repository settings. Also if you go into admin view into your repo , it will give you a direct link where you set this

A: I'm the product manager for Stash. I was unable to reproduce this issue, but if it's still causing concern please don't hesitate to contact our support team.


text:
Q: how can I define a symbol as a global real number? Say there is a complex number a=x+I, where x is a real number. Then b=Join[{a},{1+I}], and I use Re[b].
The result is {Re[x],1}, but the desired result is {x,1}.
How can I set x as a global real number from the very beginning? Please be noted that x should be treated a real number no matter what kind of calculation is used.
I have read many questions, but none is fit to my situation.
This problem bothers me for a very long time, and I hope someone can give me the answer.

A: Perhaps
ComplexExpand[Re[b], TargetFunctions -> {Re, Im}]
(*{x, 1}*)

is what you're looking for!

A: $Assumptions = x \[Element] Reals

a = x + I
b = Join[{a}, {1 + I}]
Refine[Re[b]]

i+x
{I + x, 1 + I}
{x, 1}


text:
Q: Always show submenu vertically under parent I have been trying various tries into css, I want the submenu to appair vertical when clicking on the parent..
i use this template purchased: http://livedemo00.template-help.com/wordpress_55042/
when clicking on the "Services" tab, I want the "submenu" is displayed vertically and always show under the parent
Any suggestions welcomed.


text:
Q: VS2010: How to change automatic generated XML documentation file name I recently changed my project's dll name from ObjectCreator1.1.dll to ObjectCreator.dll. This project also creates an XML documentation (Properties->Compile->Generate XML Documentation file). Now the problem is that I have renamed my assembly name with all the proper steps, and when I compile my project I get the right .dll and .pdb files, but the file name of this XML file is always ObjectCreator1._1.Template.xml. Is there any way I can rename this file to ObjectCreator.Template.xml?
I tried compiling my project without "Generate XML Documentation file" checked, and I recompiled after that with the "Generate XML doc file" checked... but somehow it is still taking the old assembly name.
Any idea from where it is taking this old name from or how I can rename it? It is a VB.NET project.

A: For a WinForms project it takes the name from the Assembly Name (specified in My Project under the Application tab).
I just changed the assembly name in my current project and recompiled, and a new XML file with the new name was generated.
For library projects, the name appears to be taken from the Root Namespace field instead.
If it's not working for you, try doing a full solution clean and rebuild.


text:
Q: gRPC sending repeated field efficiently to server I've a need to send batch of logs to server, but this log can be huge amount batch, for example 10k rows. I'm currently using repeated, but I realize repeated is taxing on memory for client side. Is there any way I could send in stream of logs together with my other parameter?
I'm currently coding in Dart, and can't figure out anyway to stream "logs" from client side to server. Is there any way I could use stream as a field to grpc server?
This is my sample .proto file
service Logger {
  //
  // Obtains the Features available within the given Rectangle.  Results are
  // streamed rather than returned at once (e.g. in a response message with a
  // repeated field), as the rectangle may cover a large area and contain a
  // huge number of features.
  rpc saveLogs(SaveLogsRequest) returns (DummyResult) {}

}

message DummyResult {
  bool success = 1;
  string error = 2;
}

message SaveLogsRequest {
  string country = 2;
  string app = 3;
  repeated Log logs = 4;
}

A: See: https://github.com/DazWilkin/dart-grpc-logger
My Dart skills are almost non-existent. This is a very basic, working example.
The code is derived from Google's route-guide sample and is here:
https://github.com/DazWilkin/dart-grpc-logger/blob/master/dart/client.dart
The server (and a second client) are written in Golang.
In one terminal, run the server:
docker run \
--interactive --tty \
--publish=50051:50051 \
dazwilkin/dart-grpc-logger-server:84a06d9cc166692ddf00c941856c96e853594695

NOTE While the server can be reconfigured to run on any available port --grpc_endpoint=..., the Dart client requires localhost:50051 because my Dart skills are limited.

The server starts, then pauses on a client:
2020/06/05 20:49:36 [main] Starting gRPC Logger Server
2020/06/05 20:49:36 [main] Creating a gRPC Server
2020/06/05 20:49:36 Starting gRPC Listener [:50051]

In another terminal, run the client:
docker run \
--interactive --tty \
--net=host \
dazwilkin/dart-grpc-logger-client:84a06d9cc166692ddf00c941856c96e853594695

NOTE The client must --net=host to be able to access the containerized server.

The client connects to the server and streams 10 randomly-sized batches of logs:
[Client:main] Entered
[Client:main] Configuring channel
[Client:main] Creating gRPC Logger Client
[Client:runSaveLogs] Entered
[Client:generateLogs] Count=10
[Client:generateLogs] Batch=1
[Client:generateLogs] Batch=4
[Client:generateLogs] Batch=4
[Client:generateLogs] Batch=4
[Client:generateLogs] Batch=7
[Client:generateLogs] Batch=8
[Client:generateLogs] Batch=7
[Client:generateLogs] Batch=7
[Client:generateLogs] Batch=8
[Client:generateLogs] Batch=9
[Client:runSaveLogs] Finished

The server receives the stream of batches of logs:
2020/06/05 20:49:47 [Server:SaveLogs] 2020-06-05T20:49:47Z Entered
2020/06/05 20:49:48 [Server:SaveLogs] Received 1 logs
2020/06/05 20:49:48 [Server:SaveLogs] 2020-06-05T20:49:48Z Log: test
2020/06/05 20:49:48 [Server:SaveLogs] Received 4 logs
2020/06/05 20:49:48 [Server:SaveLogs] 2020-06-05T20:49:48Z Log: test
2020/06/05 20:49:48 [Server:SaveLogs] 2020-06-05T20:49:48Z Log: test
2020/06/05 20:49:48 [Server:SaveLogs] 2020-06-05T20:49:48Z Log: test
2020/06/05 20:49:48 [Server:SaveLogs] 2020-06-05T20:49:48Z Log: test
2020/06/05 20:49:48 [Server:SaveLogs] Received 4 logs
2020/06/05 20:49:48 [Server:SaveLogs] 2020-06-05T20:49:48Z Log: test
2020/06/05 20:49:48 [Server:SaveLogs] 2020-06-05T20:49:48Z Log: test
2020/06/05 20:49:48 [Server:SaveLogs] 2020-06-05T20:49:48Z Log: test
2020/06/05 20:49:48 [Server:SaveLogs] 2020-06-05T20:49:48Z Log: test
2020/06/05 20:49:48 [Server:SaveLogs] Received 4 logs
2020/06/05 20:49:48 [Server:SaveLogs] 2020-06-05T20:49:48Z Log: test
2020/06/05 20:49:48 [Server:SaveLogs] 2020-06-05T20:49:48Z Log: test
2020/06/05 20:49:48 [Server:SaveLogs] 2020-06-05T20:49:48Z Log: test
2020/06/05 20:49:48 [Server:SaveLogs] 2020-06-05T20:49:48Z Log: test
2020/06/05 20:49:49 [Server:SaveLogs] Received 7 logs
2020/06/05 20:49:49 [Server:SaveLogs] 2020-06-05T20:49:49Z Log: test
2020/06/05 20:49:49 [Server:SaveLogs] 2020-06-05T20:49:49Z Log: test
2020/06/05 20:49:49 [Server:SaveLogs] 2020-06-05T20:49:49Z Log: test
2020/06/05 20:49:49 [Server:SaveLogs] 2020-06-05T20:49:49Z Log: test
2020/06/05 20:49:49 [Server:SaveLogs] 2020-06-05T20:49:49Z Log: test
2020/06/05 20:49:49 [Server:SaveLogs] 2020-06-05T20:49:49Z Log: test
2020/06/05 20:49:49 [Server:SaveLogs] 2020-06-05T20:49:49Z Log: test
2020/06/05 20:49:49 [Server:SaveLogs] Received 8 logs
2020/06/05 20:49:49 [Server:SaveLogs] 2020-06-05T20:49:49Z Log: test
2020/06/05 20:49:49 [Server:SaveLogs] 2020-06-05T20:49:49Z Log: test
2020/06/05 20:49:49 [Server:SaveLogs] 2020-06-05T20:49:49Z Log: test
2020/06/05 20:49:49 [Server:SaveLogs] 2020-06-05T20:49:49Z Log: test
2020/06/05 20:49:49 [Server:SaveLogs] 2020-06-05T20:49:49Z Log: test
2020/06/05 20:49:49 [Server:SaveLogs] 2020-06-05T20:49:49Z Log: test
2020/06/05 20:49:49 [Server:SaveLogs] 2020-06-05T20:49:49Z Log: test
2020/06/05 20:49:49 [Server:SaveLogs] 2020-06-05T20:49:49Z Log: test
2020/06/05 20:49:49 [Server:SaveLogs] Received 7 logs
2020/06/05 20:49:49 [Server:SaveLogs] 2020-06-05T20:49:49Z Log: test
2020/06/05 20:49:49 [Server:SaveLogs] 2020-06-05T20:49:49Z Log: test
2020/06/05 20:49:49 [Server:SaveLogs] 2020-06-05T20:49:49Z Log: test
2020/06/05 20:49:49 [Server:SaveLogs] 2020-06-05T20:49:49Z Log: test
2020/06/05 20:49:49 [Server:SaveLogs] 2020-06-05T20:49:49Z Log: test
2020/06/05 20:49:49 [Server:SaveLogs] 2020-06-05T20:49:49Z Log: test
2020/06/05 20:49:49 [Server:SaveLogs] 2020-06-05T20:49:49Z Log: test
2020/06/05 20:49:49 [Server:SaveLogs] Received 7 logs
2020/06/05 20:49:49 [Server:SaveLogs] 2020-06-05T20:49:49Z Log: test
2020/06/05 20:49:49 [Server:SaveLogs] 2020-06-05T20:49:49Z Log: test
2020/06/05 20:49:49 [Server:SaveLogs] 2020-06-05T20:49:49Z Log: test
2020/06/05 20:49:49 [Server:SaveLogs] 2020-06-05T20:49:49Z Log: test
2020/06/05 20:49:49 [Server:SaveLogs] 2020-06-05T20:49:49Z Log: test
2020/06/05 20:49:49 [Server:SaveLogs] 2020-06-05T20:49:49Z Log: test
2020/06/05 20:49:49 [Server:SaveLogs] 2020-06-05T20:49:49Z Log: test
2020/06/05 20:49:50 [Server:SaveLogs] Received 8 logs
2020/06/05 20:49:50 [Server:SaveLogs] 2020-06-05T20:49:50Z Log: test
2020/06/05 20:49:50 [Server:SaveLogs] 2020-06-05T20:49:50Z Log: test
2020/06/05 20:49:50 [Server:SaveLogs] 2020-06-05T20:49:50Z Log: test
2020/06/05 20:49:50 [Server:SaveLogs] 2020-06-05T20:49:50Z Log: test
2020/06/05 20:49:50 [Server:SaveLogs] 2020-06-05T20:49:50Z Log: test
2020/06/05 20:49:50 [Server:SaveLogs] 2020-06-05T20:49:50Z Log: test
2020/06/05 20:49:50 [Server:SaveLogs] 2020-06-05T20:49:50Z Log: test
2020/06/05 20:49:50 [Server:SaveLogs] 2020-06-05T20:49:50Z Log: test
2020/06/05 20:49:50 [Server:SaveLogs] Received 9 logs
2020/06/05 20:49:50 [Server:SaveLogs] 2020-06-05T20:49:50Z Log: test
2020/06/05 20:49:50 [Server:SaveLogs] 2020-06-05T20:49:50Z Log: test
2020/06/05 20:49:50 [Server:SaveLogs] 2020-06-05T20:49:50Z Log: test
2020/06/05 20:49:50 [Server:SaveLogs] 2020-06-05T20:49:50Z Log: test
2020/06/05 20:49:50 [Server:SaveLogs] 2020-06-05T20:49:50Z Log: test
2020/06/05 20:49:50 [Server:SaveLogs] 2020-06-05T20:49:50Z Log: test
2020/06/05 20:49:50 [Server:SaveLogs] 2020-06-05T20:49:50Z Log: test
2020/06/05 20:49:50 [Server:SaveLogs] 2020-06-05T20:49:50Z Log: test
2020/06/05 20:49:50 [Server:SaveLogs] 2020-06-05T20:49:50Z Log: test
2020/06/05 20:49:50 [Server:SaveLogs] 2020-06-05T20:49:50Z EOF


text:
Q: Python Regex - Select Text between a pattern Have below sample text descriptions
Input
Example 1: (Have Comments in the text)
1. ADEQUATE HANDWASHING SINKS PROPERLY SUPPLIED AND ACCESSIBLE - Comments: AN HANDWASHING SINK INSTALLED AT  EAST BAR AREA.NEED TO RELOCATE HANDWASHING SINK AT MIDDLE OF AREA  BEHIND THE BAR COUNTER FOR  ACCESSIBILITY TO HAND WASHING.  PRIORITY FOUNDATION VIOLATION :7-38-030(C), NO CITATION ISSUED.
Example 2: (No Comments in the text)
47. FOOD & NON-FOOD CONTACT SURFACES CLEANABLE, PROPERLY DESIGNED, CONSTRUCTED & USED
The Output should be like below. Need to extract all texts after starting index numbers,followed by '.' and before '- Comments:'. If no '- Comments:' found then extract all texts after the starting index numbers.
ADEQUATE HANDWASHING SINKS PROPERLY SUPPLIED AND ACCESSIBLE
FOOD & NON-FOOD CONTACT SURFACES CLEANABLE, PROPERLY DESIGNED, CONSTRUCTED & USED
Tried using the regular expression '(?:^[\d+. ]*)(.*?)(?:\-\s\w*: ?)'  which worked for example 1 but not for example 2.
Is it possible to match both examples in one regular expression?

A: Here is one regex find all approach.  We can match on the following regex:
\d+\. (.*?)(?: - |\r?\n|$)

This will match from the start of a numbered section until reaching either -, CR?LF, or the end of the input.
inp = """1. ADEQUATE HANDWASHING SINKS PROPERLY SUPPLIED AND ACCESSIBLE - Comments: AN HANDWASHING SINK INSTALLED AT EAST BAR AREA.NEED TO RELOCATE HANDWASHING SINK AT MIDDLE OF AREA BEHIND THE BAR COUNTER FOR ACCESSIBILITY TO HAND WASHING. PRIORITY FOUNDATION VIOLATION :7-38-030(C), NO CITATION ISSUED.

Example 2: (No Comments in the text)

47. FOOD & NON-FOOD CONTACT SURFACES CLEANABLE, PROPERLY DESIGNED, CONSTRUCTED & USED"""

matches = re.findall(r'\d+\. (.*?)(?: - |\r?\n|$)', inp)
print(matches)

This prints:
['ADEQUATE HANDWASHING SINKS PROPERLY SUPPLIED AND ACCESSIBLE',
 'FOOD & NON-FOOD CONTACT SURFACES CLEANABLE, PROPERLY DESIGNED, CONSTRUCTED & USED']


text:
Q: Retrieve single from pairs This is a SQL query question.
If you have a table like this:
ID1         ID2
1709    1689
1689    1709
1934    1501
1501    1934

And you want to retrieve like this:
ID1         ID2
1709    1689
1934    1501

How would you do that? Please note that (1709, 1689) and (1689, 1709) are similar pairs just the IDs being shifted. My purpose is to get a single tuple out of these similar tuples.

A: Try this, which should work in any dialect (you don't specify what product you're using) that supports CASE:
 SELECT DISTINCT
    CASE WHEN ID1 < ID2 THEN ID1 ELSE ID2 END AS ID1,
    CASE WHEN ID1 < ID2 THEN ID2 ELSE ID1 END AS ID2
    FROM Table

This converts all the rows to have the lower ID first, then uses DISTINCT to remove duplicates.


text:
Q: Size image in layout to maximum width without pushing other items out of view I am trying to layout a cell in a ListView with a header, central image and a footer.
The cells will be a fixed height and I want the image to be proportionally scaled up to the maximum width possible without pushing the footer out of the view.
Is this possible in an XML layout?
I have set up a simple example with this layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="100dp"
    >
    <TextView
        android:id="@+id/heading"
        android:textColor="#000000"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
    <ImageView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:src="@drawable/placeholder"
        />
    <TextView
        android:textColor="#000000"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="footer"/>
</LinearLayout>

The footer is not displayed when the height is constrained as above:

I understand that "match_parent" is probably not what I want for the ImageView width, but how can I configure the sizing of the image such that it will only use the available space?

A: Thanks to @I_A_Mok here is the revised layout:
<?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="150dp"
>
<TextView
    android:id="@+id/heading"
    android:textColor="#000000"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"/>
<TextView
    android:id="@+id/footer"
    android:textColor="#000000"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="footer"
    android:layout_alignParentBottom="true"/>
<ImageView
    android:layout_weight=".8"
    android:adjustViewBounds="true"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:src="@drawable/placeholder"
    android:layout_below="@+id/heading"
    android:layout_above="@+id/footer"
    />

</RelativeLayout>


text:
Q: Getting id of ui:inputCheckbox to set for attribute on label <ui:inputCheckbox/> always generates the label to the left of the checkbox in the markup, like so:
<ui:inputCheckbox aura:id="reimbursed" label="Reimbursed?" class="slds-checkbox" labelClass="slds-form-element__label" value="{!v.newExpense.Reimbursed__c}" />

becomes

    Reimbursed?
  <input class="slds-checkbox" type="checkbox" id="427:2;a">

In order to get the pretty checkboxes in SLDS, the checkbox needs to be inside the  tag, with an additional faux span to do the CSS rendering, like so:

  <input name="checkbox" type="checkbox" id="checkboxSample1" />

  Checkbox Label

In order to achieve this, I need to be able to set the for attribute on the label to the same value as the aura-generated id attribute on the checkbox. So I'm trying something like this:
<aura:component implements="force:appHostable" controller="CheckboxTestController">
  <aura:attribute name="contacts" type="Contact[]" />
  <aura:attribute name="checkedContacts" type="String[]" />
  <aura:handler name="init" value="{!this}" action="{!c.doInit}" />

    <fieldset class="slds-form-element">

        <legend>Choose contacts to add:</legend>

        <aura:iteration var="con" items="{!v.contacts}">

            <ui:inputCheckbox class="" text="{!con.Id}" aura:id="{!con.Id}" change="{!c.updateCheckboxes}"/>

            {!con.Name}

        </aura:iteration>

    </fieldset>

</aura:component>

The problem I'm having is figuring out how to populate the for on the label. I'm pretty sure setting {!con.Id} as the aura:id on the checkbox isn't working (when I tried a cmp.find('anId') it came back undefined), and I believe this is because only string literals can be used for the aura:id attribute. And I can't figure out how to get the resulting id for the for attribute in the label.
(This is similar to ui:inputCheckbox and lightning design system, but the accepted answer on that question doesn't actually resolve anything - simply removing the app.css stylesheet doesn't make <ui:inputCheckbox/> reorder the markup.)

A: It looks like http://documentation.auraframework.org/auradocs#reference?descriptor=ui:inputCheckbox&defType=component , has an attribute called "domId" which sounds like what we want, unfortunately when trying to use it I get [ERROR]: No ATTRIBUTE named domId found: Source .
However,  this attribute is not listed in the ui:inputCheckbox docs located at /auradocs . I guess because it hasn't made it over quite yet.
I'm not sure what ui:inputCheckbox really buys us in this situation, as we aren't using the div and label wrappers the component generates (it only seems to do that when we specify a label attribute, which we don't want to do since we want the slds classes and layout).
Something like this seems to work for right now:

  <input type="checkbox" id="{!contact.Id}" onchange="{!c.checkboxChange}"/>

  {!contact.Name}

({checkboxChange: function(component, event, helper){
  console.log(event.target.id);
})
Problems with this approach:
1) There can be id collisions. A temporary workaround could be adding a namespace to the id.
2) There could also be more built into the ui:inputCheckbox change event than the html5 change event, but the html5 change event seems pretty robust: https://developer.mozilla.org/en-US/docs/Web/Events/change .
Long term, I bet this is problem could be solved by the domId attribute.

A:
I have got the same problem, I need to set the "for" property for a
  checkbox dynamically generated. Any lucky?

Ok, I found a solution. Simply, when I create my new component, I retrieve the global ID and I write it to an attribute in my component. So, I can use it in the page!
component:
<aura:attribute name="globalId" type="String" access="private"/>

in the controller:
    $A.createComponents(
        newComponentList,
        function(createdNewComponentList,status, errorMessage){
            if (status === "SUCCESS") {

                var divComponent = component.find("placeholderItem");
                var divBody = divComponent.get("v.body");

                for(var i in createdNewComponentList){
                    //HERE IT IS THE MAGIC!
                    component.set('v.globalId', createdNewComponentList[i].getGlobalId());
                    divBody.unshift(createdNewComponentList[i]);
                }

                divComponent.set("v.body", divBody);
            }

            else if (status === "INCOMPLETE") {
                console.log("No response from server or client is offline.")
                // Show offline error
            }
            else if (status === "ERROR") {
                console.log("Error: " + JSON.stringify(errorMessage));
                // Show error message
            }
        }
    );


text:
Q: why should all iterators / iterator adaptors not-movable in C++11? In this question discussed When to make a type non-movable in C++11 and I discovered Scott Meyers had similar question on comp.std.c++, where SG listed below class types are not movable in C++11 libeary.

*

*all mutex types(recursive_mutex , timed_mutex, recursive_timed_mutex,

*condition_variable

*type_info

*error_category

*locale::facet

*random_device

*seed_seq

*reference_wrapper

*duration

*time_point

*- all iterators / iterator adaptors

*ios_base

*basic_istream::sentry

*basic_ostream::sentry

*all atomic types

*once_flag

The question is why is all iterators / iterator adaptors not-movable ?

A: By "not movable" with respect to iterators you probably mean that the class definition does not contain user-declared move operations. But iterators are still copyable. So, a move request still works and falls back on copying. Because of that, there is no reason to provide move operations in situations where the move operations would do exactly the same as the copy operations. For a typical iterator implementation there is nothing to optimize for w.r.t. moving.

A: That post, from a year before the standard was ratified, is outdated. The poster is Daniel Krügler, an active committee member, and it's a bit of political lobbying:

These aren't moveable and probably some more by accident, because the
  rules for implicitly generated move operations became clarified just
  at the Pittsburgh meeting. A general library issue has been opened
http://www.open-std.org/jtc1/sc22/wg21/docs/lwg-active.html#1331
to cope for lack of move support in the library. Be sure that you
  contact you national body representative, because I've heart that this
  issue is not a sufficient replacement for a national body comment
  against the FCD.

In other words, all those types being non-movable would be a showstopper bug for the standard, and he wants readers in the Usenet audience to demand that the problem be fixed before the standard becomes official.
The defect has been moved to the "closed" list. The resolution is (link provided for convenience):

Review the library portion of the spec and incorporate the newly added core feature Move Special Member Functions (N3044).

Since N3044 is a hefty bit of material, it's easy to see why it would be essential for such basic functionality to work.
Iterators, and anything else with simple value semantics like std::duration and std::time_point, are certainly movable. As others have mentioned, copyability implies movability, and if it didn't the language would be broken. This post wasn't wrong at the time; rather it's arguing about the brokenness of the unfinished language.

A: I take it you include: "classes which implement moving as ordinary copying" in your list of non-moveable types. . Iterators are considered lightweight objects which are cheap to copy. It wouldn't make sense to mandate a move operator for them. E.g. std::vector<T>::iterator essentially is just a wrapped T*, and copying them is just as cheap as moving.

A: Short answer
because they are copyable.
Long Answer
We have first to clarify what6 "move" actually means.
Von Newman machines don't move data: thy just "copy". Data are copyed form a memory location to another. never "moved".
But at higher abstraction level data can be just pointers to other data. When you copy a pointer nullifying the copyed one, the referred data are said to be "moved" from one "owner" to another.
More generally, an operation that copies a value (lake the address contained in a pointer is) and destroys the original one setting it to a recognizable "invalid" is said to be a "move".
In term of C++ whe can distinguish different type of objects:

*

*The ones containing just a simple value.

*The ones containing just a simple pointer or reference that "own" what they refer

*The ones containing just a simple pointer or reference not "owing" what they refer

*The ones containing huge values.

*The ones that represent a physical entity or an operating system (more general "hosting platform") entity.

For all of this types, the concept of "copy" and "move" may have different semantic meaning, and for some of then one operation or the other may have mo meaning at all.
Now Consider type 1 objects:
int a=5; c=0;
c = a;
c = std::move(a);

what do you expect the value of a to be after the move? What about c = a+b? Should a and b be "moved" into operator+ ?
Consider now type 2 objects:
std::unique_ptr<int> pa(new int(5)), pb;
pb = std::move(pa);

Here there are two smart pointer (both of them will be destroyed on scope exit) and only one integer.
There is an operation (the delete, in this case) that can be done only once, so only one pointer must retain the "ownership" of the integer. Thsi is the case where "copy" is meaningless, and move is the only supported operation
Now consider type 3 objects:
std::list<int> lst = { 1,2,3,4 };
auto i = lst.begin();
auto j = i;
*j = *i+5;
++i;
*i = *j;

This makes perfectly sense: it just make the list to become { 6,6,3,4 }.
Iterators don't own what they refer: there may be many of them all referring the same value. Copy makes sense, but move doesn't: if we move i into j (instad of copy) no *i and ++i wold be anymore possible.
Now consider objects of type 4:
class A
{
   int m[15000000]; //15 million integers
public:
   int& operator[](unsigned x) { return m[x]; }
   const int& operator[](unsigned x) const { return m[x]; }
};

Such a huge beast will be problematic to be allocated on the stack in the most of the systems. It will most likely leave on the heap, and owned / referred by (smart) pointers. Its address will be moved between its pointers, but the object itself will not be movable. It may still be copyable.
There is another subtle case: when A is itself a pointer to the dynamically allocated huge array: This is the same as std::vector:  It is movable since it is itself a "smart pointer" who owns the dynamically allocated data, but may be also copyable, since there may be the case you need a new different copy of the owned data.
Now cosider type 5:
class window
{
private:
   HWND handle;
public:
   window() :handle(CreateWindow(....))
   { .... }
   ~window() { DestroyWindow(handle); }
};

Here an instance of window represents a window existing on screen. What does it mean "copy" or "move"?
This is most likely the case for mutex, condition_variable, etc., where both copy and move are disabled.


text:
Q: Error when trying to get images from DocumentDirectory path I'm trying to store an array of images in DocumentDirectory path
This is my code to store the images
 let img = photo //Change to be from UIPicker
    let data = UIImagePNGRepresentation(img!)!
    do {
        let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
        try data.writeToFile("\(documentsPath)(myImage)", options: [])

    } catch {
        print("Error")
    }

And this is how I get the images
  override func viewDidLoad() {
    super.viewDidLoad()

    do {
        let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
        let readData = try NSData(contentsOfFile: "\(documentsPath)(myImage)", options: [])
        let retreivedImage = UIImage(data: readData)
        image = retreivedImage
        photos.append(image!)

    }

    catch {
        print("Error")
    }

My problem is when I save the first image I can load it but when I add more then 1 image and save it I can't reload it

A: I think this will help you. This code was working for me.
You can Download and save image to Document directory like below using swift3.0
/// Get Document directory path

var directoryPath: String {
    let baseUrl = NSSearchPathForDirectoriesInDomains(.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)

    print("Base Url: \(baseUrl.first!)")

    return baseUrl.first!
}

/// add a image to Document directory
func addImage(_ image: UIImage, name: String) -> Bool {
    var path = directoryPath

    path.append("/\(name)")

    return FileManager.default.createFile(atPath: path, contents: UIImageJPEGRepresentation(image, 1.0), attributes: nil)
}

/// fetch a image from document directory

func fetchImage(name: String) -> UIImage? {
    var imagePath = directoryPath

    imagePath.append("/\(name)")

    if  FileManager.default.fileExists(atPath: imagePath) {

        return UIImage(contentsOfFile: imagePath)!

    } else {

        return nil

    }
}


text:
Q: Importar csv sem duplicar registros Tenho uma planilha com 32000 registros, e preciso jogar para uma tabela no banco de dados. O problema é que nessa planilha não tenho o ID dos registros e não posso deixar duplicar quando fizer a importação.
Preciso fazer com que quando eu fizer a importação, ele verifique pelo campo "loja" (que é o nome/razão social da loja), caso já exista, ele deve atualizar o registro com os dados da planilha, e caso não exista, ele criará um novo registro na tabela.

A: Crie a tabela que você vai importar como chave primaria no campo "loja".
E no script de importação adicione o REPLACE.
Caso ele encontre o mesmo registro ele irá atualizar, exemplo:
LOAD DATA INFILE 'file.csv' REPLACE INTO table[...]


text:
Q: Javascript roll dice animation Hello i made roll dice function with a small animation but at the end i have a problem cuz animation doent go to the end :

      <button onclick="rolldice()">roll dice</button>

So i have die(1-6).png witch uses to show witch number was generated and i have anim(1-8).png witch i use for animation.
so inside interval i generate random number between 1-8 and then change diece1 and diece2 src attribute to the animation witch was generated everything goes well as it should but at the end of the animation ones "num" reach 60  i want to set diece1 and diece2 src to the one of d1 or d2 witch was random generated to 1-6 and then call a result image
But at the end i got the last anime image and not result image to be more clear i got anime(1-8).png instead of die(1-6).png and i was mentioned before anime pngs is for animate and die pngs is for result and i get last generated anime png ones interval stops i tried to change src outside of the interval but the result was same

A: Although you've cleared the interval, it will still finish its last run, which will result in your dice having an animation-image again.
The only thing you'll have to do, is add an else to your if-statement, like this:
if(num == 60){
    diece1.src = "die" + d1 + ".png";
    diece2.src = "die" + d2 + ".png";
    clearInterval(interval);
}else{
    diece1.src = "anim" + num1 + ".png";
    diece2.src = "anim" + num2 + ".png";
}

Hope this helps

A: change
if(num == 60){
    diece1.src = "die" + d1 + ".png";
    diece2.src = "die" + d2 + ".png";
    clearInterval(interval);
}
    diece1.src = "anim" + num1 + ".png";
    diece2.src = "anim" + num2 + ".png";

to
if(num == 60){
    diece1.src = "die" + d1 + ".png";
    diece2.src = "die" + d2 + ".png";
    clearInterval(interval);
} else {
    diece1.src = "anim" + num1 + ".png";
    diece2.src = "anim" + num2 + ".png";
}

currently the last two lines overwrite the final output stage.

A: if(num < 60){//Rolling dice
    diece1.src = "anim" + num1 + ".png";
    diece2.src = "anim" + num2 + ".png";
} else {  //Results pair up?
    diece1.src = "die" + d1 + ".png";
    diece2.src = "die" + d2 + ".png";
    diece1.src = "anim" + num1 + ".png";
    diece2.src = "anim" + num2 + ".png";
    clearInterval(interval);
}

How about that?


text:
Q: What is the relationship between the sum of a graph's vertices and its regions? I have a problem that claims that because a certain simple, connected planar graph $G$ has no simple cycles of length 4 or less, the sum of the degrees of the vertices must be greater than or equal to $5r$, where $r$ is the number of regions. Why is this?

A: Count the vertex-region incidences in two ways:

*

*Each vertex $v$ is incident not only with $\deg(v)$ edges, but also with $\deg r$ regions between these.

*Each region is incident with as many vertices as the length of its bounding cycle states. By assumption, this cycle has length $\ge 5$.

From the first point, the total number of incidences is $\sum_v \deg(v)$, from the second point it is $\ge 5r$


text:
Q: how to get date format in notepad++ Hi I have a file with a few thousand rows to be added into a MySQL database. There are date values in the rows which are in dd/mm/yyyy, d/mm/yy format but I need them to be in yyyy-mm-dd format.
eg: '11/04/2011', needs to become '2011-04-11', in every row
7/04/2011', needs to become '2011-04-07', in every row
Is there a simple way to do this in notepad++ using find and replace.

A: You can do this with Notepad++:
Find: ([0-9]+)/+([0-9]+)/+([0-9]+)
Replace: \3-\2-\1

A: To avoid a messy expression, you should do this in two passes. First you want to find/replace the dates with a two digit day:
Find: ([0-9]{2})/([0-9]{2})/([0-9]{4})
Replace: \3-\2-\1

Then you want to do the same for a single digit day:
Find: ([0-9]{1})/([0-9]{2})/([0-9]{4})
Replace: \3-\2-0\1

Please note that both the find AND replace values are different in each example (one uses a leading 0 and one doesn't for the replace). If you run the second pass first, you will end up with a lot of false positives.

A: find : (\d*)/(\d*)/(\d\d\d\d)
replace : ($3)-($1)-($2)


text:
Q: HTML5 JSON MultiDimensional Arrays Keys with javascript or jQuery? I read lots of information on the net and forums but cannot get a solution to my problem.
I have the following JSON file:
var data =
{ "AA" :[{"a1":[{"ab1": [
                     {"ab1a": 10 },
                     {"ab1b": 20 },
                     {"ab1c": 30 },
                     {"ab1d": 40 }
                     ]
            },
            {"ab2":[
                     {"ab1a": 10 },
                     {"ab1b": 20 },
                     {"ab1c": 30 },
                     {"ab1d": 40 }
                    ]
            }
            ]
     }
     ,{"a2":[{"ab3": [
                     {"ab3a": 10 },
                     {"ab3b": 20 },
                     {"ab3c": 30 },
                     {"ab3d": 40 }
                     ]
             },
            {"ab4":[
                     {"ab4a": 10 },
                     {"ab4b": 20 },
                     {"ab4c": 30 },
                     {"ab4d": 40 }
                    ]
            }
            ]
     }
    ]
}

I have validated the JSON file. I want to get the keys first for "AA" then "a1" and "a2" and then for "ab1", "ab2" and etc. There are questions and information about values but not the keys. Most probably jQuery might help but I am confused about how to get all the keys.
Any ideas? any hope...!

A: The key to getting all the keys from an object of unknown size is recursion. Here I have  2 solutions; one Functional and one Object Oriented. Also I created some other data to test with in addition to yours.
Here is the repo with the complete code: https://github.com/vasilionjea/json-keys

The Data:
var data = {
  continents: {
    europe: {
      countries: [
        {
          'country-name': 'italy',
          cities: [
            { 'city-name': 'Rome', title: 'Roma Dolor', population:873, gdb: 301 },
            { 'city-name': 'Venice', title: 'Venice Veggies.', population:456, gdb: 244 }
          ]
        },

        {
          'country-name': 'france',
          cities: [
            { 'city-name': 'Paris', title: 'De Ipsum', population:7123, gdb: 77 },
            { 'city-name': 'Marseille', title: 'La Mipsum', population:73, gdb: 7 }
          ]
        }
      ]
    },

    'north-america': {
      countries: [
        {
          'country-name': 'canada',
          cities: [
            { 'city-name': 'Montreal', title: 'The city of lorem ipsum!', population:99, gdb: 011 },
            { 'city-name': 'Quebec', title: 'Veggie Ipsum.', population:123, gdb: 101 }
          ]
        },
        {
          'country-name': 'usa',
          cities: [
            { 'city-name': 'New York', title: 'Empire State', population:1001001, gdb: 1010 },
            { 'city-name': 'San Francisco', title: 'SF Bridge', population:20123, gdb: 202 }
          ]
        }
      ]
    }
  }
}

The functional way:
/*
 * Functional example.
 * Retrieves all keys from an object of unknown size using recursion.
 */
function _isObject(obj) {
  return Object.prototype.toString.call(obj) === "[object Object]";
}

function _eachKey(obj, callback) {
  Object.keys(obj).forEach(callback);
}

var _container = [];

function collectKeys(data) {
  _eachKey(data, function(key) {
    _container.push(key);

    if (_isObject(data[key])) {
      collectKeys(data[key]);
    }

    if (Array.isArray(data[key])) {
      // Because we're looping through an array and each array's item is an object,
      // the `collectKeys` function is receiving each object of the array as an argument.
      data[key].forEach(collectKeys);
    }
  });

  return _container;
}

// Execute the function
var myKeys = collectKeys(data);

The Object Oriented way:
/*
 * Object Oriented example.
 * Retrieves all keys from an object of unknown size using recursion.
 */
function JSONKeys(obj) {
  this._container = [];

  if (this._isObject(obj)) {
    // Just a normal object literal.
    this._data = obj;
  } else if (typeof obj === 'string') {
    // Just in case the data was passed in as a valid JSON string.
    this._data = JSON.parse(obj);
  } else {
    throw new Error('The provided argument must be an object literal or a JSON string.');
  }
}

JSONKeys.prototype = {
  constructor: JSONKeys,

  _isObject: function(obj) {
    return Object.prototype.toString.call(obj) === "[object Object]";
  },

  _eachKey: function(obj, callback) {
   // Using `bind(this)` makes sure that the `this` value in the `_collect` method
   // isn't set to the global object (window).
    Object.keys(obj).forEach(callback.bind(this));
  },

  _recur: function(key, data) {
      // If this key's value is also an object go deeper.
      if (this._isObject(data[key])) {
        this._collect(data[key]);
      }

      if (Array.isArray(data[key])) {
        // * Because we're looping through an array and each array's item is an object,
        //   the `_collect` method is receiving each object of the array as an argument.
        // * Using `bind(this)` makes sure that the `this` value in the `_collect` method
        //   isn't set to the global object (window).
        data[key].forEach(this._collect.bind(this));
      }
  },

  _collect: function(data) {
    this._eachKey(data, function(key) {
      this._container.push(key);

      // Continue collecting
      this._recur(key, data);
    });
  },

  getAll: function() {
    this._collect(this._data);
    return this._container;
  }
};

// Create a new instance passing the data.
var keysObject = new JSONKeys(data);
allKeys = keysObject.getAll();


text:
Q: How to optimize the SQL query to the Oracle database I have an SQL query to the Oracle database
(The query links the elements to the clusters related by the clusters by having the maximum average connection to each element of the cluster. The relationship of two elements is defined by number of links they have in common. We calculate the relation of the given element to the each element of the cluster, then take the relation of the element to the cluster as average of relations of this elements to all elements of the cluster, then pick the cluster to which our element has maximal relation and add the element to the cluster )
INSERT INTO t_clusters (transaction_id,
                    CLUSTER_ID,
                    word_id,
                    connection)
SELECT 72,
      CLUSTER_ID,
      word_id,
      avg_cnt
 FROM (  SELECT word_id, CLUSTER_ID, AVG (cnt) avg_cnt
           FROM (  SELECT a.word_id,
                          b.word_id bword,
                          c.CLUSTER_ID,
                          COUNT (*) cnt
                     FROM t_semantic a,
                          t_words a1,
                          t_semantic b,
                          t_clusters c
                    WHERE     a.transaction_id = 72
                          AND a.word_id = a1.word_id
                          AND a1.checked = 0
                          AND CLUSTER_ID <> 0
                          AND a.link_id = b.link_id
                          AND b.word_id = c.word_id
                 GROUP BY a.word_id, b.word_id, c.CLUSTER_ID)
       GROUP BY word_id, CLUSTER_ID
         HAVING AVG (cnt) >= 3) zz
WHERE avg_cnt = (SELECT MAX (avg_cnt)
                   FROM (  SELECT AVG (cnt) avg_cnt, word_id
                             FROM (  SELECT a.word_id,
                                            b.word_id bword,
                                            c.CLUSTER_ID,
                                            COUNT (*) cnt
                                       FROM t_semantic a,
                                            t_words a1,
                                            t_semantic b,
                                            t_clusters c
                                      WHERE     a.transaction_id = 72
                                            AND a.word_id = a1.word_id
                                            AND a1.checked = 0
                                            AND CLUSTER_ID <> 0
                                            AND a.link_id = B.link_id
                                            AND b.word_id = c.word_id
                                   GROUP BY a.word_id,
                                            b.word_id,
                                            c.CLUSTER_ID)
                         GROUP BY word_id, CLUSTER_ID
                           HAVING AVG (cnt) > 3) zzy
                  WHERE zzy.word_id = zz.word_id)

It executing already 23 hours
The number of records in the table of relations (t_semantic) is 532125
The number of records in the table of clusters (t_clusters) where stored elements, already connected to clusters is 23014
The number of records in the table with elements not connected to clusters yet (t_words) is 36111
Fields word_id, cluster_id, link_id indexed in all table.
Is it any way to improve the perfomance of this query and why it's so slow?
Plan
INSERT STATEMENT  ALL_ROWSCost: 9,234
    28 FILTER
        10 HASH GROUP BY  Cost: 9,234  Bytes: 46,000  Cardinality: 2,000
            9 VIEW  Cost: 9,234  Bytes: 8,599,493  Cardinality: 373,891
                8 SORT GROUP BY  Cost: 9,234  Bytes: 15,329,531  Cardinality: 373,891
                    7 HASH JOIN  Cost: 5,215  Bytes: 15,329,531  Cardinality: 373,891
                        1 TABLE ACCESS FULL TABLE DKIM.T_WORDS Cost: 86  Bytes: 286,568  Cardinality: 35,821
                        6 HASH JOIN  Cost: 5,117  Bytes: 20,274,408  Cardinality: 614,376
                            4 HASH JOIN  Cost: 2,245  Bytes: 4,108,540  Cardinality: 205,427
                                2 INDEX FAST FULL SCAN INDEX (UNIQUE) DKIM.UK_CLUSTER Cost: 333  Bytes: 229,140  Cardinality: 22,914
                                3 TABLE ACCESS FULL TABLE DKIM.T_SEMANTIC Cost: 1,903  Bytes: 5,277,070  Cardinality: 527,707
                            5 TABLE ACCESS FULL TABLE DKIM.T_SEMANTIC Cost: 1,909  Bytes: 6,859,632  Cardinality: 527,664
        27 SORT AGGREGATE  Bytes: 26  Cardinality: 1
            26 VIEW  Cost: 18  Bytes: 26  Cardinality: 1
                25 FILTER
                    24 SORT GROUP BY  Cost: 18  Bytes: 23  Cardinality: 1
                        23 VIEW  Cost: 18  Bytes: 23  Cardinality: 1
                            22 SORT GROUP BY  Cost: 18  Bytes: 41  Cardinality: 1
                                21 TABLE ACCESS BY INDEX ROWID TABLE DKIM.T_CLUSTERS Cost: 4  Bytes: 10  Cardinality: 1
                                    20 NESTED LOOPS  Cost: 17  Bytes: 41  Cardinality: 1
                                        18 NESTED LOOPS  Cost: 9  Bytes: 93  Cardinality: 3
                                            15 NESTED LOOPS  Cost: 5  Bytes: 21  Cardinality: 1
                                                12 TABLE ACCESS BY INDEX ROWID TABLE DKIM.T_WORDS Cost: 2  Bytes: 8  Cardinality: 1
                                                    11 INDEX UNIQUE SCAN INDEX (UNIQUE) DKIM.T_WORDS_PK Cost: 1  Cardinality: 1
                                                14 TABLE ACCESS BY INDEX ROWID TABLE DKIM.T_SEMANTIC Cost: 3  Bytes: 13  Cardinality: 1
                                                    13 INDEX RANGE SCAN INDEX DKIM.IND_SEMANTIC_WORD_ID Cost: 2  Cardinality: 1
                                            17 TABLE ACCESS BY INDEX ROWID TABLE DKIM.T_SEMANTIC Cost: 4  Bytes: 30  Cardinality: 3
                                                16 INDEX RANGE SCAN INDEX DKIM.IND_SEMANTIC_LINK_ID Cost: 2  Cardinality: 3
                                        19 INDEX RANGE SCAN INDEX DKIM.CLUSTERS_WORD_ID Cost: 2  Cardinality: 1

A: Using analytic functions to determine the max avg_cnt might help speed things up, e.g.:
insert into t_clusters (transaction_id,
                        cluster_id,
                        word_id,
                        connection)
select 72,
       cluster_id,
       word_id,
       avg_cnt
 from  (select   word_id,
                 cluster_id,
                 avg(cnt) avg_cnt,
                 max(avg(cnt)) over (partition by word_id) max_avg_cnt
        from     (select   a.word_id,
                           b.word_id bword,
                           c.cluster_id,
                           count (*) cnt
                  from     t_semantic a,
                           t_words a1,
                           t_semantic b,
                           t_clusters c
                  where    a.transaction_id = 72
                  and      a.word_id = a1.word_id
                  and      a1.checked = 0
                  and      cluster_id <> 0
                  and      a.link_id = b.link_id
                  and      b.word_id = c.word_id
                  group by a.word_id, b.word_id, c.cluster_id)
        group by word_id, cluster_id
        having   avg(cnt) >= 3)
where  avg_cnt = max_avg_cnt;


text:
Q: How to install `aide` without `aide-common` in debian? Per this post,

Newer versions of Ubuntu (including 14.04) come with two packages for
AIDE:
aide, with the aide command and manual page, and little else

aide-common, with a wrapper around that command, configuration files with rules, and cron configuration files that will cause AIDE to be run nightly

If your AIDE is bundled like this, attempts to run the aide command
directly will fail with the message:
Couldn't open file
/var/lib/aide/please-dont-call-aide-without-parameters/aide.db for
reading
even when parameters are supplied.
The configuration files are in different places, and to configure and
use AIDE, the executables from aide-common must be used instead:
aideinit, aide.wrapper, update-aide.conf, and aide-attributes.

In Debian 10,when you apt install aide,aide-common also be installed.
How to install aide without aide-common in debian?

A: From apt-cache depends aide we can see that it's only reccomended:
[~]$ apt-cache depends aide
aide
  Conflicts: aide-dynamic
  Conflicts: aide-xen
  Recommends: aide-common
  Suggests: figlet

If it said Depends: aide-common it would be a hard requirement. Recommends is only a soft dependency, so you can choose to ignore it.
If we from there go on to man apt-get, to learn how apt-get works and search for recommends we find this:

   --no-install-recommends
      Do not consider recommended packages as a dependency for
      installing. Configuration Item: APT::Install-Recommends.

So the command apt-get install --no-install-recommends aide should install aide without installing aide-common.