text:
Q: dynamodb row count via python, boto query Folks,
  Am trying to get the following bit of code working to return the row count in a table:
import boto
import boto.dynamodb2
from boto.dynamodb2.table import Table
from boto.dynamodb2.fields import HashKey, RangeKey

drivers = Table('current_fhv_drivers')
rowcountquery = drivers.query(
   number = 'blah',
   expiration = 'foo',
   count=True,
  )
for x in rowcountquery:
 print x['Count']

Error I see is:
boto.dynamodb2.exceptions.UnknownFilterTypeError: Operator 'count' from 'count' is not recognized.

Whats the correct syntaxt to get row count :)
Thanks!

A: That exception is basically telling you that the operator 'count' is not recognized by boto.
If you read the second paragraph on http://boto.readthedocs.org/en/latest/dynamodb2_tut.html#querying you'll see that:

Filter parameters are passed as kwargs & use a __ to separate the fieldname from the operator being used to filter the value.

So I would change your code to:
import boto
import boto.dynamodb2
from boto.dynamodb2.table import Table
from boto.dynamodb2.fields import HashKey, RangeKey

drivers = Table('current_fhv_drivers')
rowcountquery = drivers.query(
   number__eq = 'blah',
   expiration__eq = 'foo',
   count__eq = True,
  )
for x in rowcountquery:
 print x['Count']

A: from boto.dynamodb2.table import Table
table = Table('current_fhv_drivers')
print(table.query_count(number__eq = 'blah', expiration__eq = 'foo'))


text:
Q: Process is in interruptible sleep - how to find out what it is waiting for I have an daemon running on Debain on Arm. Sometimes this daemon hangs/is not responding anymore. When looking at the process with "ps ax" the stat column is "Dl" which means "uninterruptible sleep (usually IO)". Is it possible to find out more details on what the process is waiting - for example which IO is hanging?
Thanks!

A: I had the same question with Jetson Nano (ARMv8, kernel architecture: aarch64), which hanging on ptxas command.
First we neet to understand what does process in uninterruptible sleep state mean. Read this: What is an uninterruptible process? and Linux process states.
In short: the process in the uninterruptible sleep can by only woken by what it's waiting for. It can't be woken up by any signal.
To investigate what is going on, you can check stack of process
cat /proc/<PROCESS_PID>/stack

In my case it was
[nano]<$:~$ sudo cat /proc/6816/stack
[<ffffff80080863bc>] __switch_to+0x9c/0xc0
[<ffffff80081c6fdc>] wait_on_page_bit_killable+0x8c/0x98
[<ffffff80081c7948>] __lock_page_or_retry+0xc0/0xe8
[<ffffff80082029b8>] do_swap_page+0x5d0/0x840
[<ffffff8008204be4>] handle_mm_fault+0x60c/0xa68
[<ffffff80080a36b0>] do_page_fault+0x308/0x518
[<ffffff80080a392c>] do_translation_fault+0x6c/0x80
[<ffffff8008080954>] do_mem_abort+0x54/0xb0
[<ffffff80080833c8>] el0_da+0x20/0x24
[<ffffffffffffffff>] 0xffffffffffffffff

How do I stop that from happening?

It's depend on the case. In my case I increased the swap size.

This is probably a dumb question, but is there any way to interrupt it without restarting my computer?

Process in uninterruptible sleep state may occasionally change to interruptible state and then goes back to the previous uninterruptible state again. So, you can try
while true; do kill -9 <PROCESS_PID>; done

redpajama_set_name: RedPajamaStackExchange


text:
Q: Where is \@makefntext defined? I was studying how footnotes come about in LaTeX and what processes exactly run behind the curtain, and noticed \@makefntext. But in fact, in latex.ltx there are only two occurences of this macro where it gets called and no actual definition can be found. Does it implicitly get defined by some wrapper command? Or does it happen in another file? Or even both?

A: To find definitions, you may use latexdef command.
Example (using the -s option to try to show the original source code of the command definition and the -c option to load given class):

latexdef -s -c article @makefntext

produces:
% article.cls, line 619:
\newcommand\@makefntext[1]{%
    \parindent 1em%
    \noindent
    \hb@xt@1.8em{\hss\@makefnmark}#1}

A: With a little help of grep: The standard classes define this command:
For example article.cls
Within \maketitle:
\long\def\@makefntext##1{\parindent 1em\noindent
        \hb@xt@1.8em{%
            \hss\@textsuperscript{\normalfont\@thefnmark}}##1}%

Later on in the class:
\newcommand\@makefntext[1]{%
    \parindent 1em%
    \noindent
    \hb@xt@1.8em{\hss\@makefnmark}#1}

Inletter.cls
  \long\def\@makefntext#1{%
    \noindent
    \hangindent 5\p@
    \hb@xt@5\p@{\hss\@makefnmark}#1}

The definitions from book and report classes are equal to article.cls, for the KOMA classes the definition is somewhat different.


text:
Q: Simple closed curves in torus. Suppose $a$ and $b$ are two simple closed curves in a one genus orientable surface, i.e the torus $K$. Assume that $a$ and $b$ intersects transversely at only one crossing in $K$. That means  $a$ is not homologous to $b$ in  $K$ and each is not homologous to zero in $K$. Let $l_1$, $l_2$ and $l_3$ be three simple closed homologous non-trivial curves in $K$ (non-trivial curve means it is not homologous to zero). Since these three curves are homologous in $K$, they can be represented by parallel curves in $K$. We use the notation (p,q) to represent any simple closed curve in $K$, where $(1,0)$ is the meridian and $(0,1)$ is the longitude of $K$. Suppose $a$ meets transversely each of the three curves $l_1$, $l_2$ and $l_3$ at a single crossing point. Similarly, $b$ meets transversely each of the three curves $l_1$, $l_2$ and $l_3$ at a single crossing point. I try to get the representation $(p,q)$ of $a$ and $b$. I found one possibility for the representation which is  $a=(1,0)$ and $b=(1,1)$, equivalently $a=(0,1)$ and $b=(1,1)$. I wonder if there is any other possiblility for $a$ and $b$.

A: This question isn't well defined, and I don't see a reason to have three $l$ curves.  If you are looking to find triples of curves that pairwise intersect in a single point, then there are infinitely many choices even after fixing one of the three curves.  For example, $(1,0)$, $(n,1)$, and $(n+1,1)$.  The triples of curves with this property are exactly the triangles in the Farey diagram.


text:
Q: Send Soap Request with .PFX file via php I try to do SOAP request with .pfx file and i got error like:
SOAP-ERROR: Parsing WSDL: Couldn't load from
 : failed to load external entity
my code look like that :
    $this->api_url = "https://wsa.clalbit.co.il/CalcCampaignPremia.asmx?WSDL";

    $certificate   = dirname( __FILE__ ) . '/ws-hova.pfx';
    $options       = array(
        'cache_wsdl' => WSDL_CACHE_NONE,
        'trace'          => 1,
        'local_cert'     => $certificate,
        'stream_context' => stream_context_create( array(
            'ssl' => array(
                'verify_peer'       => false,
                'verify_peer_name'  => false,
                'allow_self_signed' => true
            )
        ) )
    );

    try {
        $this->soap = new SoapClient( $this->api_url, $options );
    } catch (SoapFault $e) {
        echo $e->getMessage();
    }

can't understand why it is not working.
thank's for any advice

A: The native PHP soap client class can not work with pfx certificates. You have to turn your pfx file into a pem file. For this purpose install the openssl toolkit and run the following command in your shell / command line interface.
openssl pkcs12 -in ws-hova.pfx -out ws-hova.pem -nodes -clcerts

After you 've done creating a pem certificate out of your pfx certificate you can simply use it with the PHP soap client.
$certificate = dirname( __FILE__ ) . '/ws-hova.pem';
$options = [
    'cache_wsdl' => WSDL_CACHE_NONE,
    'exceptions' => true,
    'trace' => true,
    'local_cert' => $certificate,
    'authentication' => SOAP_AUTHENTICATION_DIGEST,
];

try {
    $client = new SoapClient( $this->api_url, $options );
} catch (SoapFault $e) {
    echo $e->getMessage();
}

This will do the trick. ;)
Have fun.


text:
Q: How to import JavaScript libraries with ViteJS in HTML? I am using ViteJS to npm install any libraries or packages that I need, and I plan to use vanilla JavaScript and HTML.  One of the libraries I am using is called os-gui, a styling library.  The docs state that I can use npm install it, but also calls for directly importing the library in the HTML like this:

Since I am not using ReactJS but ordinary HTML, and since I have not directly downloaded the library, how can I properly format the href so that it points to the correct packages that I downloaded in npm?


text:
Q: How to force all uploaded images to be JPG I have looked around for information about this but haven't been able to find what I am looking for.
I have a site where users are able to upload an image for display on their user profile.
However, what I want to do is be able to make every photo that is uploaded a jpg. I feel like forcing people to only upload JPG files isn't good, but if I am able to make all files JPG, then that would be great.
Here is my code for when a user uploads an image:
require('includes/config.php');

// Upload and Rename File

if (isset($_POST['submit']))
{
    $filename = $_FILES["file"]["name"];
    $file_basename = substr($filename, 0, strripos($filename, '.')); // get file extention
    $file_ext = substr($filename, strripos($filename, '.')); // get file name
    $filesize = $_FILES["file"]["size"];
    $allowed_file_types = array('.jpg','.jpeg','.png','.gif');

if (in_array($file_ext,$allowed_file_types) && ($filesize < 2000000))
{
    // Rename file
    $newfilename = ($_SESSION['memberID']) . $file_ext;
    if (file_exists("upload/" . $newfilename))
    {
        // file already exists error
        echo "You have already uploaded this file.";
    }
    else
    {
        move_uploaded_file($_FILES["file"]["tmp_name"], "uploads/" . $newfilename);
        echo "File uploaded successfully.";
    }
}
elseif (empty($file_basename))
{
    // file selection error
    echo "Please select a file to upload.";
}
elseif ($filesize > 200000)
{
    // file size error
    echo "The file you are trying to upload is too large.";
}
else
{
    // file type error
    echo "Only these file typs are allowed for upload: " . implode(', ',$allowed_file_types);
    unlink($_FILES["file"]["tmp_name"]);
}

If anyone is able to suggest a way of changing uploaded files to JPG then please let me know.

A: Try this code: originalImage is the path of... the original image... outputImage is self explaining enough. Quality is a number from 0 to 100 setting the output jpg quality (0 - worst, 100 - best)
function convertImage($originalImage, $outputImage, $quality)
{
    // jpg, png, gif or bmp?
    $exploded = explode('.',$originalImage);
    $ext = $exploded[count($exploded) - 1];

    if (preg_match('/jpg|jpeg/i',$ext))
        $imageTmp=imagecreatefromjpeg($originalImage);
    else if (preg_match('/png/i',$ext))
        $imageTmp=imagecreatefrompng($originalImage);
    else if (preg_match('/gif/i',$ext))
        $imageTmp=imagecreatefromgif($originalImage);
    else if (preg_match('/bmp/i',$ext))
        $imageTmp=imagecreatefrombmp($originalImage);
    else
        return 0;

    // quality is a value from 0 (worst) to 100 (best)
    imagejpeg($imageTmp, $outputImage, $quality);
    imagedestroy($imageTmp);

    return 1;
}


text:
Q: How I can pass a parameter value in where clause MongoDB i have a problem with a mongoDb query, i need to search for a parameter value of any MongoDB field.
I use a function in $where clause like:
db.response.find(
{
    $where: function() {
        var deepIterate = function  (obj, value) {
            for (var field in obj) {
                if (obj[field] == value){
                    return true;
                }
                var found = false;
                if ( typeof obj[field] === 'object') {
                    found = deepIterate(obj[field], value)
                    if (found) { return true; }
                }
            }
            return false;
        };
        return deepIterate(this, "Text36")
    }
});

The returned response was fine but I don't know how I can pass the value (Text36 in this sample) I want to found like a parameter
can someone help me please ? Thanks


text:
Q: why left join is faster than where exists when both the table A and B contains 10 million records If there are 2 tables TableA and TableB. I want to find all the records of TableA which are not present in TableB, I can use Left join or where exists.
My question is that if there are 10 Million records in both the table which method will give better performance Left join or Where exists.?. I know Left join performs better But can someone tell me why?. I was asked this question in interview why where exists will perform slow than Left join when records are more.


text:
Q: Android - how to use the same instance of a control on all activities I have a custom user control which is included in all activities and it contains a progress bar control in it. When this control becomes visible in the screen, the progress bar gets updated with the current progress.
I want to make this control a "single instance" type of control so that if the progress bar's progress is updated in a particular screen, it gets reflected in the new screen as well.
I can do this by storing the current progress in, say SharedPreferences or a static variable and have it checked to display the progress in the new screen.
But I want to know is there a better approach to design & layout such a control or have a type of "Single Instance" (keeping in mind memory leaks) control that can be included in multiple screens?

A: You can use a Fragment to achieve this.
"A Fragment represents a behavior or a portion of user interface in an Activity. You can combine multiple fragments in a single activity to build a multi-pane UI and reuse a fragment in multiple activities"


text:
Q: GParted for one partition http://imgur.com/9PRkseB
I have one partition as in picture above. I want to create 50GB of partition to install Windows. How can I do that? Thanks !

A: You can't resize the root partition.
If I were you, I'll Backup my data and try GParted with Live CD.
Kindly notice that you don't have a swap area.


text:
Q: How to get Activity's transition? I can set transition to an activity use overridePendingTransition.
But I can't find method to get these transition.Which API should I use?
for example, some code has used overridePendingTransition to set transition for Activity A.
Now I have Activity B, it need same transition of B. But the overridePendingTransition operation to A is invisible to me .
So I need API to get A's transition. I can't find it after searching the API document.


text:
Q: Параллельные процессы в c# Есть задача: читать из таблицы в бд ms SQL некоторую колонку с путями к файлам и копировать их по заданному адресу. Если решать все последовательно, то все элементарно: считать из бд данные в какой-нибудь список, а потом выполнить копирование. Но на мой взгляд это не рационально, ведь таблица может быть здоровенной и очень много полезного времени в холостую. Подскажите, как можно реализовать параллельный алгоритм вида: взять топ 100 записей из таблице, кинь в очереди в методе копирования, пока копирование идет извлечь еще100 записей и пополнить очередь.
Может быть сможете привести примеры чего-нибудь похоже или классы, которые мне понадобятся или статьи с примерами?

A: Я бы не стал делить на пакеты по 100 файлов, а реализовал бы с помощью ConcurrentQueue. Одна задача вычитывает имена файлов, заполняя очередь, другая её разбирает. Та, которая разбирает, создаёт некоторое ограниченное (с помощью SemaphoreSlim) количество задач копирования.
Примерная реализация в консольном приложении:
using System;
using System.Collections.Concurrent;
using System.Data.SqlClient;
using System.IO;
using System.Threading;
using System.Threading.Tasks;

class Program
{
    static ConcurrentQueue<string> queue = new ConcurrentQueue<string>();
    static ManualResetEvent evtFileQueued = new ManualResetEvent(false);
    static SemaphoreSlim sem = null;
    static Task tQueueFill = null;

    static void Main()
    {
        int MaxCopyTasks = Math.Max(1, Environment.ProcessorCount - 2);
        sem = new SemaphoreSlim(MaxCopyTasks);

        tQueueFill = QueueFill();
        tQueueFill.Start();
        Task tQueueProcess = QueueProcess();
        tQueueProcess.Start();

        Task.WaitAll(tQueueFill, tQueueProcess);

        while (sem.CurrentCount < MaxCopyTasks)
            Thread.Sleep(500);
    }

    static async Task QueueFill()
    {
        SqlConnection connection = new SqlConnection("...");
        SqlCommand cmd = new SqlCommand("select FileName from TableName", connection);

        using (var dr = await cmd.ExecuteReaderAsync())
            while (dr.Read())
            {
                queue.Enqueue((string)dr[0]);
                evtFileQueued.Set();
            }
    }

    static async Task QueueProcess()
    {
        while (true)
        {
            if (tQueueFill.IsCompleted || tQueueFill.IsFaulted || tQueueFill.IsCanceled)
                break;

            if (!evtFileQueued.WaitOne(250))
                continue;

            while (!queue.IsEmpty)
            {
                if (!await sem.WaitAsync(0))
                    break;

                string fileName = null;
                if (queue.TryDequeue(out fileName))
                {
                    Task tCopy = new Task(CopyFile, fileName);
                    tCopy.Start();
                }
                else
                    sem.Release();
            }

            if (queue.IsEmpty)
                evtFileQueued.Reset();
        }
    }

    static void CopyFile(object param)
    {
        string fileName = (string)param;
        string fileNameDest = Path.Combine("Directory", fileName);
        File.Copy(fileName, fileNameDest);
        sem.Release();
    }
}

A: OrdinalPartitioner<MyItem> partitioner = Partitioner.Create(items);

IList<IEnumerator<MyItem>> paritions = partitioner.GetPartitions(
    Environment.ProcessorCount);

Task[] tasks = partitions.Select(p => Task.Run(() => {
        using (var ctx = new MyDbContext())
        using (p)
        while (p.MoveNext())
        {
            MyItem current = p.Current;

            ctx.DoSomething1(current);
            ctx.DoSomething2(current);
        }
    })).ToArray();

Partitioner Class


text:
Q: Multimedia Keys not working? I have tried out Keytouch and successfully created a new keyboard file and also successfully applied it. But still my multimedia keys are not working. I am using lubuntu 14.04 and audacious for audio and gnome mplayer for video. Please help me out here please.
Thank you.

A: Guess currently multimedia keys work with rhythmbox, but not audacious or banshee.

A: In Audacious I was going to File -> Preferences -> General Tab -> And enabled check at "Gnome Shortcuts".
All of my multimedia keys now work with Audacious.  :)
Enjoy!

A: In Audacious plugins settings you can try to enable "Global Hotkeys" and "MPRIS 2 Server".


text:
Q: Sitecore global header Just wondering what the best practice is to set a global header that can be overridden on certain pages if may need be?
For example there is google tracking code applied globally (to the whole site) and on one form it needs to have its own tracking code and the global one removed?
I have tried creating a code block and setting the standard values in the Item Template although only applies the code to a newly created page but does not apply to existing pages. This would mean that one would have to add the code to each individual page.
thanks

A: When I have had to implement solutions such as this I would either create a template called 'Site settings' and inherit it from the homepage (or create a item using this template) and then write some extension methods for the Site class. Storing the ID of the settings item in the Web.config is something I usually prefer to avoid to I usually just attach the template to the homepage.
That way I can end up with the following.
<%=Sitecore.Context.Site.Settings.AnalyticsCode()%>

This particular extension method would first look at the context item to see if the 'Analytics code' field is populated, if it is not then I grab the homepage and get the field from there instead.
This method of course allows you to expand with a number of handy extension methods available from your context site or context item.

A: You can create a kind of setting item in the Sitecore tree with the field and add that field to the selected pages as well. Then use the code similar to this:
<%= (!String.IsNullOrEmpty(Sitecore.Context.Item["GoogleId"]))
    ? Sitecore.Context.Item["GoogleId"]
    : MySettingsItem["GoogleId"] %>

A: This sounds like a decent usage of "Field Fallback." Essentially, each page (Item) in your site would have the Google Tracking Code field. You would wire up some sort of Fallback mechanism to use the value on the current item, or look up the tree until you find a value. This would allow you to set the Google Tracking Code at the 'Home' item and all descendants would use the value, unless it was explicitly set at a lower level.
See my (Sean Kearney's) blog post on the subject of fallback.
Here is a link to my Field Fallback shared source module.


text:
Q: How To Call Variable Name From Another Class C# Example of the code
class Main{
        Name Jack = new Name();
        Jack.Speak();
}

class Name{
     public string speak(){
        Console.WriteLine("Hello", valuename);
      }

     public Name()
     {
       valuename = nameof(Jack);
     }
}

Output the what im searching for:
Hello Jack.

If user types Name Joe = new Name(); output will be Hello Joe.

A: Local variable names are syntactical sugar that is mostly thrown away by the compiler, so there's no direct way to do this.
The closest you can get is using [CallerArgumentExpression] to have the compiler capture the source code expression that was passed to a parameter, but this only works for method arguments and will capture the entire expression, not just the variable name. For example, the following program will print jack then jack + "hello":
using System;
using System.Runtime.CompilerServices;

class Program {
    static void Main()
    {
        var jack = "dummy";
        WriteExpression(jack);
        WriteExpression(jack + "hello");
    }

    static void WriteExpression(
        string param,
        [CallerArgumentExpression("param")] string paramExpression = null
    ) => Console.WriteLine(paramExpression);
}


text:
Q: How to have the result of a UNION overwrite a table records I am a beginner in SQL.  I would like the results of a UNION of linked tables tblCandidates and tblCandidatesArchive to overwrite the data in tblInvites.   This UNION works:
SELECT tblCandidates.INPUT_NUMBER, tblCandidates.Booked, tblCandidates.Call_1, tblCandidates.Call_2, tblCandidates.Call_3, tblCandidates.Call_4, tblCandidates.[BizO RESULTS], tblCandidates.CallResults_1, tblCandidates.CallResults_2, tblCandidates.CallResults_3, tblCandidates.CallResults_4
FROM tblCandidates

WHERE (((tblCandidates.Call_1)>Date()-366) AND ((tblCandidates.CallResults_1)="eMailed Info" Or (tblCandidates.CallResults_1)="Biz Overview")) OR (((tblCandidates.Call_2)>Date()-366) AND ((tblCandidates.CallResults_2)="eMailed Info" Or (tblCandidates.CallResults_2)="Biz Overview")) OR (((tblCandidates.Call_3)>Date()-366) AND ((tblCandidates.CallResults_3)="eMailed Info" Or (tblCandidates.CallResults_3)="Biz Overview")) OR (((tblCandidates.Call_4)>Date()-366) AND ((tblCandidates.CallResults_4)="eMailed Info" Or (tblCandidates.CallResults_4)="Biz Overview"))

UNION

SELECT  tblCandidatesArchive.INPUT_NUMBER, tblCandidatesArchive.Booked, tblCandidatesArchive.Call_1, tblCandidatesArchive.Call_2, tblCandidatesArchive.Call_3, tblCandidatesArchive.Call_4, tblCandidatesArchive.[BizO RESULTS], tblCandidatesArchive.CallResults_1, tblCandidatesArchive.CallResults_2, tblCandidatesArchive.CallResults_3, tblCandidatesArchive.CallResults_4
FROM tblCandidatesArchive

WHERE (((tblCandidatesArchive.Call_1)>Date()-366) AND ((tblCandidatesArchive.CallResults_1)="eMailed Info" Or (tblCandidatesArchive.CallResults_1)="Business Overview")) OR (((tblCandidatesArchive.Call_2)>Date()-366) AND ((tblCandidatesArchive.CallResults_2)="eMailed Info" Or (tblCandidatesArchive.CallResults_2)="Business Overview")) OR (((tblCandidatesArchive.Call_3)>Date()-366) AND ((tblCandidatesArchive.CallResults_3)="eMailed Info" Or (tblCandidatesArchive.CallResults_3)="Business Overview")) OR (((tblCandidatesArchive.Call_4)>Date()-366) AND ((tblCandidatesArchive.CallResults_4)="eMailed Info" Or (tblCandidatesArchive.CallResults_4)="Business Overview"))
ORDER BY tblCandidates.Call_1 DESC

But as soon as I add this to the beginning of the SQL query statement it errors with a long syntax error (missing operator) in query expression '(((tblCandidates.Call_1)>Date()-366) and
WHERE(((tblCandidatesArchive.Call_)>Date()-366) AND('.

INSERT INTO tblInvites (INPUT_NUMBER, Booked, Call_1, Call_2, Call_3, Call_4, [BizO Results], CallResults_1, CallResults_2, CallResults_3, CallResults_4)

It took me a while to get the UNION working.  I looked at the suggested links when posting.  I also Googled.  I am having problems finding anything which does exactly what I am trying to do.
Your help is much appreciated.

A: An all-in-one statement using UNION as data source for an INSERT SELECT must follow syntax like:
INSERT INTO table(field1, field2) SELECT field1, field2 FROM (union query SQL here)

The UNION data source is a nested SQL without a terminating semi-colon between parentheses.


text:
Q: Collapse button in Twitter bootstrap navbar not clickable When my navbar collapses the links and dropdown hide correctly and the button to display them shows but is not clickable.
If I replace my navbar with the code on the bootstrap page then the bootstrap example bar and collapse button performs correctly, so it is a problem with my HTML somewhere..
My code is:

    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
      Toggle navigation

    </button>

        MarcB

<%= link_to "Blog", posts_path %>

<%= link_to 'Contact', contact_path %>

    <% if current_user %>

 <%= link_to "Sign Out", logout_path %>

 Signed in as:  <%= current_user.name %>

    <% else %>

           Log in

<%= link_to 'Log in with Facebook', "/auth/facebook" %>

<%= link_to 'Log in with LinkedIn', "/auth/linkedin" %>

<%= link_to 'Log in with GitHub', "/auth/github" %>

<%= link_to 'Log in with Google+', "/auth/gplus" %>

    <% end %>

and the generated HTML from rails is (not signed in)

    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
      Toggle navigation

    </button>

        MarcB

Blog

Contact

           Log in

Log in with Facebook

Log in with LinkedIn

Log in with GitHub

Log in with Google+

I have also tried commenting out the second ul with the dropdown - produces the same unclickable button.

A: Put high z-index on button e.g.
button {
  position: relative;
  z-index: 100000;
}


text:
Q: How do I retrieve null values in my database to a view I have a simple Employee Database which allows me to add new a employee, with some of my textbox fields left empty (I'm using winform). It currently works ok in the database. It registers NULL values in place of the empty textboxes. My problem now is how to display all the employees from the database in a gridview:
When I run the program, it pops up a messagebox saying "object cannot be cast from DBNull to other types". Is it because 'age' and 'married' columns in my database contain some null values? Please help, I'm trying to understand how to use nullable types in c# with mssql database.
   public static List<Employee> GetEmployees()
    {
        List<Employee> empListToReturn = new List<Employee>();
        SqlConnection conn = GetConnection();
        string queryStatment = "SELECT * FROM Employee";
        SqlCommand sqlCmd = new SqlCommand(queryStatment, conn);
        try
        {
            conn.Open();
            SqlDataReader reader = sqlCmd.ExecuteReader();
            while (reader.Read())
            {
                Employee emp = new Employee();
                emp.FirstName = reader["firstname"].ToString();
                emp.LastName = reader["lastname"].ToString();
                emp.Age = Convert.ToInt32(reader["age"]);
                emp.Married = (reader["married"]);

                empListToReturn.Add(emp);
            }
            reader.Close();
        }
        catch (SqlException ex)
        {
            throw ex;
        }
        finally
        {
            conn.Close();
        }
        return empListToReturn;

    }

A: As the error states, you can't convert null to other types.  Specifically in this case an int:
emp.Age = Convert.ToInt32(reader["age"]);

(Since value types can't be null.)
Simply check for null before converting:
if (reader["age"] == DBNull.Value)
    emp.Age = 0;
else
    emp.Age = Convert.ToInt32(reader["age"]);

Edit: As pointed out in a comment, there are multiple ways to do this.  Some may be more efficient than others.  For example:
if (reader.IsDBNull(reader.GetOrdinal("age")))
    emp.Age = 0;
else
    emp.Age = reader.GetInt32(reader.GetOrdinal("age")));

Unless the performance difference is significant, I'd probably prefer the former when using named columns instead of the ordinal, since this requires an extra method call to get the ordinal.  (Unless there's a string overload that I'm just not seeing on MSDN?)

Additionally, if you don't want 0 as an option, you might change the .Age property from int to Nullable<int> (or int? for short).  This would allow you to set a null value on that object:
if (reader.IsDBNull(reader.GetOrdinal("age")))
    emp.Age = null; // <-- here
else
    emp.Age = reader.GetInt32(reader.GetOrdinal("age")));

This is often very useful when there's a clear semantic difference between 0 (which is a valid value) and null (which is a lack of a value).

It's also worth noting that this code is bad practice:
catch (SqlException ex)
{
    throw ex;
}

Not only is your catch block not actually handling the exception at all, it's actually overwriting the stack trace.  Which would make debugging more difficult.  Since the catch block isn't doing anything, just remove it entirely.  You don't need a catch in a try/finally.


text:
Q: How to fix line breaks in the text cdr file? i have following output from cdr file as shown in the below code snippet.
2021-10-27 00:06:53,203:16344:5:0:4:573192000019::6:0:4:573160001511:*999#:1:1:573160032001:1:6:732123904909775:1:1:573156068892:::::SUCCESS:PULL:2021-10-2700:06:53.203:101630:20076482:28389:2
,2:aa8c2b31-ac49-4c16-9e2f-f8a83ba63cd6
2021-10-27 00:06:57,120:16344:5:0:4:573192000019::6:0:4:573160001511:*111#:1:1:573160032002:1:6:732123907508180:1:1:573134396303:::::SUCCESS:PULL:2021-10-27 00:06:57.12:101631:26706476:11566:3,3,3192244169:d21e7dca-6dfa-43e6-8bcd-b95ebd35cdea

As can be seen in the Code Snippet, line number 2 should be part of line number 1, but there is a line break splitting the transaction into two lines. The requirement is following.
2021-10-27 00:06:53,203:16344:5:0:4:573192000019::6:0:4:573160001511:*999#:1:1:573160032001:1:6:732123904909775:1:1:573156068892:::::SUCCESS:PULL:2021-10-2700:06:53.203:101630:20076482:28389:2,2:aa8c2b31-ac49-4c16-9e2f-f8a83ba63cd6
2021-10-27 00:06:57,120:16344:5:0:4:573192000019::6:0:4:573160001511:*111#:1:1:573160032002:1:6:732123907508180:1:1:573134396303:::::SUCCESS:PULL:2021-10-27 00:06:57.12:101631:26706476:11566:3,3,3192244169:d21e7dca-6dfa-43e6-8bcd-b95ebd35cdea

How can this be done in already generated file  ? There are thousands of similar lines in the cdr file which needs to corrected .TIA

A: $ awk '{printf "%s%s", (/^[0-9]{4}(-[0-9]{2}){2}/ ? ors : ""), $0; ors=ORS} END{print ""}' file
2021-10-27 00:06:53,203:16344:5:0:4:573192000019::6:0:4:573160001511:*999#:1:1:573160032001:1:6:732123904909775:1:1:573156068892:::::SUCCESS:PULL:2021-10-2700:06:53.203:101630:20076482:28389:2,2:aa8c2b31-ac49-4c16-9e2f-f8a83ba63cd6
2021-10-27 00:06:57,120:16344:5:0:4:573192000019::6:0:4:573160001511:*111#:1:1:573160032002:1:6:732123907508180:1:1:573134396303:::::SUCCESS:PULL:2021-10-27 00:06:57.12:101631:26706476:11566:3,3,3192244169:d21e7dca-6dfa-43e6-8bcd-b95ebd35cdea

A: awk -F ':' 'NF!=37 { curr=$0; getline; $0 = curr $0 }1' file

Output:

2021-10-27 00:06:53,203:16344:5:0:4:573192000019::6:0:4:573160001511:*999#:1:1:573160032001:1:6:732123904909775:1:1:573156068892:::::SUCCESS:PULL:2021-10-2700:06:53.203:101630:20076482:28389:2,2:aa8c2b31-ac49-4c16-9e2f-f8a83ba63cd6
2021-10-27 00:06:57,120:16344:5:0:4:573192000019::6:0:4:573160001511:*111#:1:1:573160032002:1:6:732123907508180:1:1:573134396303:::::SUCCESS:PULL:2021-10-27 00:06:57.12:101631:26706476:11566:3,3,3192244169:d21e7dca-6dfa-43e6-8bcd-b95ebd35cdea

I assume that each row should have 37 columns.
See: 8 Powerful Awk Built-in Variables – FS, OFS, RS, ORS, NR, NF, FILENAME, FNR

A: This might work for you (GNU sed):
sed ':a;N;/\n....-..-.. ..:..:..,/!s/\n//;ta;P;D' file

Open a 2 line window in the pattern space.
If the second line does not begin with a date and time, remove the newline (append line 2 to line 1), append the next line and repeat until failure.
Print/delete the first of the two lines and repeat.

A: Would you please try the following:
awk '
/^[[:digit:]]{4}-[[:digit:]]{2}-[[:digit:]]{2}/ {       # if the record starts with a date
    if (line) print line                                # flush the line buffer
    line = ""
}
{
    line = line $0                                      # append the current record to the line buffer
}
END {
    if (line) print line                                # flush the line buffer at the end of the file
}
' file.txt

Output with the provided example:
2021-10-27 00:06:53,203:16344:5:0:4:573192000019::6:0:4:573160001511:*999#:1:1:573160032001:1:6:732123904909775:1:1:573156068892:::::SUCCESS:PULL:2021-10-2700:06:53.203:101630:20076482:28389:2,2:aa8c2b31-ac49-4c16-9e2f-f8a83ba63cd6
2021-10-27 00:06:57,120:16344:5:0:4:573192000019::6:0:4:573160001511:*111#:1:1:573160032002:1:6:732123907508180:1:1:573134396303:::::SUCCESS:PULL:2021-10-27 00:06:57.12:101631:26706476:11566:3,3,3192244169:d21e7dca-6dfa-43e6-8bcd-b95ebd35cdea


text:
Q: VBA script in excel to find and highlight text I am looking for a VBA script that will help me find certain keywords in a cell and if found highlight the entire row. Below are my requirements:
I have a database of words eg hell, get out, shut up, don't you dare etc. I need a macro to search the data in column "E" of excel and in case any of the cell in column "E" contains any word listed in the database (irrespective of the case of the word upper or lower)the entire row is highlighted. The word can be in the beginning, middle or end of the cell and the macro should be able to find that word and highlight the column.
Seeking help from all VBA masters for this.

A: You can do this with conditional formatting, instead of VBA.
Conditional formatting works by applying a 'second formula' to a given cell. If the 'second formula' results in TRUE, then special formatting conditions can be applied.
EXAMPLE CONDITIONAL FORMATTING
For example, if you have a single column of Data, A:A, and you want to check if that column has the exact string "hello world", you could add a conditional format [Home ribbon, Styles section, Conditional Formatting] that turns a cell yellow with this formula:
=$A1="hello world"

This will only result in TRUE if the cell in column A at that row equals exactly "hello world" [note that Column A has an absolute-reference $, and row 1 does not, so row 1 is relative to the position of the cell in the condiitonal format rule].
To check to see if any row in column A includes hellow world, we need to add a SEARCH function, which checks to see if a small search string is inside of a larger string:
=SEARCH("hello world",$A1)>0

Because SEARCH by default returns the first character in a larger string that matches the search term (and if it finds nothing, it returns #N/A), we check to see if our search for "hello world" in column A returns a number.
SEARCHING MULTIPLE COLUMNS
Now, to see if ANY column, say from A-D, includes "hello world", we concatenate each value of each column so that it gives us a single string, which we can search through for "hello world", like so:
=SEARCH("hello world",$A1&$B1&$C1&$D1)>0

This will first create a single string, equal to A1 & B1 & C1 & D1 all in a row. Then it will search that newly created string to see if "hello world" is inside it, and return a number value if it is.
ARRAY FORMULA BASICS
Finally, we need to do the tricky part - searching for multiple terms instead of just "hello world". This is called an Array Formula. An array formula works by performing a single operation on multiple cells, and then returning multiple results in an Array. In an Excel sheet, an array formula must be confirmed with CTRL + SHIFT + ENTER (instead of just ENTER), but in conditional formatting, you actually don't need to do anything special - it will recognize an array formula without a special command.
As an example of conditional formatting, see this example, which checks whether any value from A1:A5 = 10, and if it does, it gives us the value in B1:B5:
=IF(A1:A5=10,B1:B5,"")

Remember in Excel on a worksheet, this would be confirmed by pressing CTRL + SHIFT + ENTER. If you do test this, it will give you the following result, assuming A2 = 10 and A5 = 10:
={"";B2;"";"";B5}

This result would actually be hidden, because Excel can't "collapse" an array function on its own. So assume column B had values, and we actually want to sum them together. We would then wrap the Array formula in a SUM function:
=SUM(IF(A1:A5=10,B1:B5,""))

As you can see if you test this, we have actually created our own SUMIF function, using Array formulas instead of the built-in SUMIF.
SEARCHING FOR MULTIPLE TERMS WITH ARRAY FORMULAS
So now we apply these principles to the conditional formatting, to create an array formula which will check our concatenated 'NEW STRING' for any number of provided terms, as follow [Assumes the search terms are typed into cells E1:E10]:
=SUM(SEARCH($E$1:$E$10,$A1&$B1&$C1&$D1)>0)

This formula can be placed as a conditional formatting rule which reaches all of A:D. Set the rule to highlight / change format in whatever way you like.


text:
Q: Error reading a CSV file I am very new PHP. Can some please solve my problem?
The following code works absolutely fine when i tried to execute using xampp in windows. But it dosen't work on Ubuntu when i try executing through ssh terminal.
Following is the php warning. but when i tried it on windows it works fine for all the records in CSV (it gives me insert or update statement for each record in the CSV)

PHP Warning:  feof() expects parameter 1 to be resource, boolean given in /home/myetexts/Documents/codes/Pearson/test2.php on line 8
  PHP Warning:  fgetcsv() expects parameter 1 to be resource, boolean given in /home/myetexts/Documents/codes/Pearson/test2.php on line 9

<?php
    ini_set('max_execution_time', 10000);
    $file = fopen('NZ_Price_list.csv', 'r');
    $count = 0;
    $con=mysql_connect("localhost","root","");
    mysql_select_db('newlocalabc');

    while(!feof($file)){
        $record = fgetcsv($file);
        if(!empty($record[0])){
           // echo 'ISBN: '.$record[0].'
';
        $price =round(($record[11])/0.85,2);
        if($record[3]== "Higher Education" || $record[3] == "Vocational Education"){
            $price =round((($record[11])/0.85)/0.97,2);
        }
        $sql = 'SELECT * FROM `products` WHERE `isbn` = '.$record[0];
        $result = mysql_query($sql);
        if(mysql_num_rows($result)){
            $data = mysql_fetch_object($result);

            $nsql = "UPDATE `products` SET `price` = '".$price."', `cover` = 'pics/cover4/".$record[0].".jpg', `cover_big` = 'pics/cover4/".$record[0].".jpg' WHERE `products`.`isbn` = ".$record[0].";";
        }else{
            $nsql = "INSERT INTO `products` (`id`, `isbn`, `title`, `publisher_id`, `description`, `supplier_id`, `price`, `author`, `cover`, `cover_big`, `status_id`, `timestamp`)
            VALUES (NULL, '".$record[0]."', '".addslashes($record[1])."', '7','Not Available', '72', '".$price."', '".$record[2]."', 'pics/cover4/".$record[0].".jpg', 'pics/cover4/".$record[0].".jpg', '0',CURRENT_TIMESTAMP);";
        }
        echo $nsql.'
';
        //echo $price.'
';
        //echo '
'; print_r($record);exit;
        }
        unset($record);
        $count++;
    }
    fclose($file);
    ?>

Hoping to hear back from some one soon.

A: The call
   fopen('NZ_Price_list.csv', 'r');

fails. A failing call doesn't return a so called PHP resource, but a boolean. Possible reasons are these:

*

*File does not exist - file_exists()

*Application can't open file for reading - is_readable()

Please be more specific an e.g. use an absolute file path like this and do some sanity checks:
$filePath = dirname( __FILE__ ) . '/..somePath../NZ_Price_list.csv';

// Ensure, that file exists and is reable
if ( ! file_exists( $filePath )) {
   throw new Exception( 'File does not exist: ' . $filePath , 10001 );
}
if ( ! is_readable( $filePath )) {
    throw new Exception( 'File not readable: ' . $filePath , 10002 );
}

// Then, try to open the file
$fileHandle = fopen( $filePath, 'r');

if ( ! is_resource( $fileHandle )) {
   throw new Exception( 'Failed to open file: ' . $filePath , 10003 );
}

Furtermore, PHP's stat() call might help. stat() provides details of a file - but can fail too...


text:
Q: Laravel: Array to string conversion Error message I'm trying to make search function and having problem. I have Array to string conversion error message.
Could you teach me right code please?
Here is this program usage
1.User select value then click [search] button (This is search.blade.php)
2.Search result will display at result.blade.php
my Laravel Framework is 6.18.8
search.blade.php
    <form action="{{ route('search') }}" class="form-image-upload" method="POST" enctype="multipart/form-data">
 {!! csrf_field() !!}

                TYPE
                <select name="type" class="form-control">
                <option value="-" selected>-</option>
                <option value="j">j</option>
                <option value="w">w</option>
                </select>

                wc
                <select name="wc" class="form-control">
                <option value="N0" selected>0</option>
                <option value="N1">1</option>
                <option value="N2">2</option>
                <option value="N3">3</option>
                </select>

                FC
                <select name="fc" class="form-control">
                <option value="0" selected>0</option>
                <option value="f01">f01</option>
                <option value="f02">f02</option>
                <option value="f03">f03</option>
                </select>

                YC
                <select name="yc" class="form-control">
                <option value="0" selected>0</option>
                <option value="yc1">yc1</option>
                <option value="yc2">yc2</option>
                </select>

                SC
                <select name="sc" class="form-control">
                <option value="Z01" selected>Z01</option>
                <option value="Z02" selected>Z02</option>
                <option value="Z03" selected>Z03</option>
                </select>

            <button type="submit" class="btn btn-success">Search</button>

</form>

result.blade.php
 {!! csrf_field() !!}

        @if($images->count())
            @foreach($images as $image)

            image }}">
                image }}" />

        @endforeach
    @endif

ImageGalleryController.php
public function search()

{
    $images = ImageGallery::get();
    return view('search',compact('images'));
}

public function order(Request $request)
{

    $data = $request->all();
    $images = ImageGallery::where(['type',$request->$data['type']],
        ['wc',$request->$data['type']],
        ['fc',$request->$data['fc']],
        ['yc',$request->$data['yc']],
        ['sc',$request->$data['sc']])->get();

    return view('result',compact('images'));
}

Web.php
// search section
Route::post('search', 'ImageGalleryController@order');
Route::get ('search', 'ImageGalleryController@search');

UPDATE
Curent my controller
public function search()

    {
        $images = ImageGallery::get();
        return view('search',compact('images'));
    }

    public function order(Request $request) {

        $data = $request->all();

        $images = ImageGallery::where([
            ['type', $data['type']],
            ['wc',$data['type']],
            ['fc',$data['fc']],
            ['yc',$data['yc']],
            ['sc',$data['sc']]
        ])->get();

         dd($images);
        return view('search', compact('images'));

        }

A: *

*Add csrf token in your form.

     @csrf

*Change order function as:
public function order(Request $request) {
$data = $request->all();

$images = ImageGallery::where([
    ['type', $data['type']],
    ['wc',$data['type']],
    ['fc',$data['fc']],
    ['yc',$data['yc']],
    ['sc',$data['sc']]
])->get();
return view('result', compact('images'));

}

*Give name method to route:
Route::post('search', 'ImageGalleryController@order')->name('search');

A: Check this code:
search.blade.php
<form action="{{ route('search') }}" class="form-image-upload" method="POST" enctype="multipart/form-data">
    {!! csrf_field() !!}

        TYPE
        <select name="type" class="form-control">
            <option value="" selected>Please Select</option>
            <option value="j">j</option>
            <option value="w">w</option>
        </select>

        wc
        <select name="wc" class="form-control">
            <option value="" selected>Please Select</option>
            <option value="N0">0</option>
            <option value="N1">1</option>
            <option value="N2">2</option>
            <option value="N3">3</option>
        </select>

        FC
        <select name="fc" class="form-control">
            <option value="" selected>Please Select</option>
            <option value="f01">f01</option>
            <option value="f02">f02</option>
            <option value="f03">f03</option>
        </select>

        YC
        <select name="yc" class="form-control">
            <option value="" selected>Please Select</option>
            <option value="yc1">yc1</option>
            <option value="yc2">yc2</option>
        </select>

        SC
        <select name="sc" class="form-control">
            <option value="" selected>Please Select</option>
            <option value="Z01">Z01</option>
            <option value="Z02">Z02</option>
            <option value="Z03">Z03</option>
        </select>

        <button type="submit" class="btn btn-success">Search</button>

</form>

result.blade.php

    @if($images->count())
        @foreach($images as $image)

            image }}">
                image }}" />

        @endforeach
    @endif

ImageGalleryController.php
public function search()
    {
        $images = \App\ImageGallery::get();

        return view('search', compact('images'));
    }

    public function order(Request $request)
    {

        $data = $request->all();

        $images = \App\ImageGallery::when($data['type'], function ($query, $type) {
            return $query->where('type', $type);
        })->
        when($data['fc'], function ($query, $fc) {
            return $query->orWhere('fc', $fc);
        })->
        when($data['yc'], function ($query, $yc) {
            return $query->orWhere('yc', $yc);
        })->
        when($data['wc'], function ($query, $wc) {
            return $query->orWhere('wc', $wc);
        })->
        when($data['sc'], function ($query, $sc) {
            return $query->orWhere('sc', $sc);
        })
        ->get();

        return view('result', compact('images'));
    }

This is the database structure:

This is the full working code on my local system.
This is web.php file
Route::get ('search', 'ImageGalleryController@search');
Route::post('search', 'ImageGalleryController@order')->name('search');

A: You have to change something. Because your $data is an array. But you have declare as an object. For this reason you get this error.
$data = $request->all();

$images = ImageGallery::where(['type'=>$data['type']],
    ['wc'=>$data['type']],
    ['fc'=>$data['fc']],
    ['yc'=>$data['yc']],
    ['sc'=>$data['sc']])->get();


text:
Q: Incorrect syntax near 'unsigned' en SQL Server estoy intentando crear una simple tabla y no puedo:
CREATE TABLE departamento (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    nombre VARCHAR(50) NOT NULL
);

Alguien sabe cuál es el problema? por mas sencillo que parezca no lo encuentro, gracias

A: Me parece que es un malentendido, hay dos puntos a comentar:
• 1) unsigned es usado en MySQL para permitir valores positivos de de 0 hasta 4294967295.
En MySQL, siempre que definimos un UNSIGNED en cualquier columna significa que no puede usar números negativos, el rango máximo con INT UNSIGNED es 4294967295.
Documentación MySQL:
https://dev.mysql.com/doc/refman/8.0/en/integer-types.html
Pero en el caso de SQL Server si defines tu campo como tipo INT este aceptara de forma predeterminada valores desde -2147483648 hasta 2147483647, por lo tanto no se tiene que especificar "unsigned" en SQL Server, de hecho esto no existe en SQL Server.
Documentación SQL Server:
https://docs.microsoft.com/en-us/sql/t-sql/data-types/int-bigint-smallint-and-tinyint-transact-sql?view=sql-server-ver15
• 2) En el caso de MySQL se usa AUTO_INCREMENT para definir un campo autoincrementable pero en SQL server se usa IDENTITY
por lo tanto tu script para crear la tabla debería ser:
CREATE TABLE departamento (
    id INT IDENTITY PRIMARY KEY,
    nombre VARCHAR(50) NOT NULL
);


text:
Q: I am trying to fit an CuDNNLSTM model and I am getting an error I am learning about recurrent neural networks and I found out CuDNNLSTM layer, which is much faster than usual LSTM. So, I have tried to fit a CuDNNLSTM model, but the only thing, which program display is "Epoch 1" and then nothing is happening and my kernel is dying (I am working in jupyter-notebook). In jupyer terminal I have find this:

2022-05-25 22:22:59.693801: I
tensorflow/stream_executor/cuda/cuda_dnn.cc:384] Loaded cuDNN version 8100
2022-05-25 22:23:00.149065: E tensorflow/stream_executor/cuda/cuda_driver.cc:1018] failed to
synchronize the stop event: CUDA_ERROR_LAUNCH_FAILED: unspecified
launch failure
2022-05-25 22:23:00.149218: E
tensorflow/stream_executor/gpu/gpu_timer.cc:55] INTERNAL: Error
destroying CUDA event: CUDA_ERROR_LAUNCH_FAILED: unspecified launch
failure
2022-05-25 22:23:00.150008: E
tensorflow/stream_executor/gpu/gpu_timer.cc:60] INTERNAL: Error
destroying CUDA event: CUDA_ERROR_LAUNCH_FAILED: unspecified launch
failure
2022-05-25 22:23:00.150355: F
tensorflow/stream_executor/cuda/cuda_dnn.cc:217] Check failed:
status== CUDNN_STATUS_SUCCESS (7 vs. 0)Failed to set cuDNN stream.

I have installed tensorflow-gpu and compatible CuDNN and CUDA to my tensorflow version
tensorflow version: 2.9.0
CUDA version: 11.2
CuDNN version: 8.1
I have tried also same model, but with LSTM layers and that have worked, but still it is very slow, so I want to figure out how to use a CuDNNLSTM model.
My code:
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, LSTM
from tensorflow.compat.v1.keras.layers import CuDNNLSTM

mnist = tf.keras.datasets.mnist

(X_train, y_train), (X_test, y_test) = mnist.load_data()

X_train = X_train/255.0
X_test = X_test/255.0

model = Sequential()

model.add(CuDNNLSTM(128, input_shape=(X_train.shape[1:]), return_sequences=True))
model.add(Dropout(0.2))

model.add(CuDNNLSTM(128))
model.add(Dropout(0.2))

model.add(Dense(32, activation="relu"))
model.add(Dropout(0.2))

model.add(Dense(10, activation="softmax"))

opt = tf.keras.optimizers.Adam(learning_rate=1e-3, decay=1e-5)

model.compile(loss="sparse_categorical_crossentropy",
              optimizer=opt,
              metrics=["accuracy"])

model.fit(X_train, y_train, epochs=3, validation_data=(X_test, y_test))

If somebody had same problem or know how to fix that, I will be grateful for help.
Thanks in an advance.

A: Have you tried this with the tanh activation function?  From my understanding, it has to use that.  Details below:

Long Short-Term Memory layer - Hochreiter 1997.
See the Keras RNN API guide
for details about the usage of RNN API.
Based on available runtime hardware and constraints, this layer
will choose different implementations (cuDNN-based or pure-TensorFlow)
to maximize the performance. If a GPU is available and all
the arguments to the layer meet the requirement of the cuDNN kernel
(see below for details), the layer will use a fast cuDNN implementation.
The requirements to use the cuDNN implementation are:

*

*activation == tanh

*recurrent_activation == sigmoid

*recurrent_dropout == 0

*unroll is False

*use_bias is True

*Inputs, if use masking, are strictly right-padded.

*Eager execution is enabled in the outermost context.


text:
Q: Sending infopath forms via email (as attachment) to be parsed by SQL Server 2005? Just looking at the requirements of a new project and I wanted to make sure this use case was sound:

*

*user fills in InfoPath (2003) form locally on their PC

*a button within the InfoPath form titled 'submit' brings up a new outlook (2003) email message with the infopath form attached. User presses sends and email is sent to an exchange mailbox.

*sql server preiodically checks this mailbox, downloading any new submissions with the infopath form attached

*sql server parses the attachment and the fields within the infopath form.

Is SQL Server capable of parsing mail attachments this way? Any caveats with this approach?
The attraction to using Outlook as the submission technology is that the process for the user is the same if they are offline. Outlook will then automatically sync when they come back online. It is essential that users have some way to fill the forms in offline, 'submit' them, and then have then synced automatically with the server when they next come online.
edit: to clarify, I am not looking for a way to cache form data from the server->client. I am looking to cache the completed form. Building a separate application to cache the completed reports on the client is not an option.

A: I would not use the approach you outlined above. There are several approaches that appear to me to be more desirable than having SQL Server looking at an Exchange Mailbox. The major point that you make and an important requirement is that the InfoPath form be allowed to work in offline mode. I would think of the "offline mode" and the "data transfer" parts of your project as two distinct and separate pieces: 1) The form and the data should be stored on the client until a connection to the Internet is available and 2) once the connection is available the form and data should be transferred to the server.
You can setup your InfoPath form to submit directly to the SQL Server and bypass the Exchange "middleman" entirely. The setup in InfoPath when you are designing your form is pretty straight forward: 1) you enable "Submit data" for the connection and 2) you configure the submit options. This article has the details about how to do that. Furthermore, your connection to the SQL Server may be setup for offline use, as it's discussed in this article. The only caveat with this approach is that you may need to change your database schema to support it.
Another approach is to have your InfoPath form submit to a SQL Server 2005 HTTP Endpoint. The InfoPath client is just a glorified XML Editor and the HTTP Endpoint is basically a different name for a web service. You receive the form data at the HTTP endpoint into a staging table where the data is stored as XML and then you can do your parsing of that data from that staging area. Still you will have to setup the InfoPath connection for offline use. The major caveat with this approach is that Microsoft will deprecate HTTP Endpoint in SQL Server 2008 in favor of WCF.
And the other approach I would like to suggest is to use WCF itself to receive the XML form data from the InfoPath client. This approach would require you to connect the form's data source to you WCF web service at design time and then also setting up the form for offline use.
I hope that this will be useful to you and at the very least point you in the right direction.

A: Later versions of SQL Server are capable of running .NET code within them, and as such you might be able to poll a mailbox from SQL Server and process an InfoPath form. However, I'm not sure I'd do it this way.
It might be better to consider writing a Windows Service that does this work. The Windows Service would start up, inspect the mail box of a "service account", read the mails, extract the attachments, process the xml and, eventually, write the data to SQL. It could also, presumably, respond to that mail with a confirmation or errors if business rules or validation errors occurred.
I'm not sure I'd put all of the above logic into SQL - for one thing, I suspect you'd have issues with accounts (having to have the account SQL was running under be able to access the Exchange mailbox account).
Your mileage may vary, and you should prototype this to determine what works best for you, but I'd try and keep the code the uses Exchange as a "work queue" separate from SQL and only put the code that deals with writing data into tables in SQL.

A: I've seen similar projects that resorted to an Express edition on the client, save the infopath (or app data) in Express and use Service Broker to deliver to center, because of guaranteed delivery semantics of SSB vs. mail. This gives you an all SQL solution easier to sell to IT and you don't need polling on the server. Also you will not have to deal with MIME parsing, is all straight forward XML processing. It is not for the faint of heart though, getting SSB up and running is a challenge.
If you decide to go with mail delivery, an external service will be arguably easier to build, debug and troubleshoot. There are some finer point issues you should have an answer for:
-How will you keep consistent the mail dequeue operations and the table write operations? Your component must engage the Exchange read/delete and the SQL insert into one distributed transaction.
- Is your logic prepared to deal with infopath docs coming out of order? mail transport makes absolutely no guarantee about the order of delivery, so you may see an 'order delete' doc before the 'order create' doc
- How are you going to detect missing documents (not delivered by mail)? Are you going to implement a sender sequence number and end up reinventing TCP on top of mail?
- Does your processing allow for parallel process of correlated documents? If thread 1 picks up doc 1 and thread 2 picks up doc 2 from same sender and doc 2 is correlated with doc 1 (ie. refer to same business transaction), what will happen at the database write? Will it deadlock, will it loose an update, will one be rolled back?
There are many dragons under the bridge ahead...


text:
Q: Prevent Privileged User from Denying Access to SA I have to set up a system where UserA has almost full control over a database (not the server), except for one table that's used by sa, and so sa will always need access to this table.
So far I have:
-- executing as sa
CREATE SCHEMA [sa_schema];
CREATE TABLE [sa_schema].[table1] ( ... );
GRANT SELECT , REFERENCES ON OBJECT::[sa_schema].[table1] TO PUBLIC

CREATE USER [UserA] WITHOUT LOGIN;
GRANT CONTROL TO [UserA] WITH GRANT OPTION;
DENY ALTER , DELETE , INSERT , TAKE OWNERSHIP , VIEW CHANGE TRACKING , UPDATE
  ON SCHEMA::[sa_schema] TO [UserA];
DENY ALTER ON USER::[sa] TO [UserA];

I thought this would be sufficient, but it turns out that it's not. It's perfectly legal for UserA to run:
-- executing as UserA
CREATE ROLE [Denied]
DENY SELECT ON OBJECT::[sa_schema].[table1] TO [Denied]
ALTER ROLE [Denied] ADD MEMBER [sa]

And now sa can no longer read from this table.
-- executing as sa
SELECT * FROM [sa_schema].[table1]

Msg 229, Level 14, State 5, Line 2
The SELECT permission was denied on the object 'table1', database 'mydb', schema 'sa_schema'.

Of course, sa could query the database to find out roles it has been added to and remove itself from them, but that seems like a kludge and a lot of work just to perform a select. I think I could avoid this problem by making sure UserA doesn't have the ability to add sa to any database roles or by ensuring UserA cannot modify the permissions on this object, so no matter what roles sa would be added to there's never going to be a DENY on this object.
Does anybody have any ideas on how to make sure sa will always have access to this table regardless of what other changes UserA makes?

A: SA is a login just like any other.  You may want to do some research on best practices regarding the SA account.  It does not need to have superpowers.
Members of the sysadmin role, however, cannot be locked out of anything and members of this role bypass security checks.  If SA is a member of sysadmin, there shouldn't be anything you need to do.
A programmatic approach could be to create a SQL Agent job that restores the correct (according to you) memberships for administrator accounts.  Set this to run on a schedule and you're guaranteed to have the permissions restored (unless UserA decided to mess with the job).
However, this is really more of a personnel issue.  The people that have this level of permission on a server should be experienced and trustworthy enough not to mess with the administrative level permissions.  If they don't know what they are doing, they should not be able to do it.  If they know what they are doing and do it any way, you have a different problem.  This may best be handled by a business policy indicating that anyone that messes with administrative level permissions may be subject to disciplinary action.

A: I think I've figured it out a convoluted way to do it. I have to change the DENY to:
DENY CONTROL ON SCHEMA::[sa_schema] TO [UserA];

This has two effects:

*

*It's a lot more difficult for UserA to select from the table despite it being public:
CREATE USER [foo] WITHOUT LOGIN;
EXECUTE AS USER = 'foo';
SELECT * FROM [sa_schema].[table1];

*It's not possible to modify permissions on the table:
CREATE ROLE [Denied];
ALTER ROLE [Denied] ADD MEMBER [sa];                     -- fine
DENY SELECT ON OBJECT::[sa_schema].[table1] TO [Denied]; -- error

Msg 15151, Level 16, State 1, Line 16
Cannot find the object 'table1', because it does not exist or you do not have permission.

This still feels a bit kludgey, but it's better than making sa reset its permissions constantly.

A: This question is completely crazy starting from attempts to give/deny permissions to sysadmin finishing with manipulations with SA user. There cannot be any SA user in database, you just not permitted to execute
create user sa from login sa

This attempt will always failed with error
Msg 15405, Level 16, State 1, Line 1
Cannot use the special principal 'sa'.


text: Q: how do I get functionality like javap in kotlin? Whenever we type javap java.lang.Number in the command line. The command outputs all the associated members of the class. This is a very helpful to determine all the members of a class and for further research on various methods, constructors etc. But, I don't know a way how to achieve this thing in kotlin class. Can anyone tell me how inspect classes in Kotlin


text:
Q: How to shade a monochrome image How can my Postscript draw a monochrome (black/white) image embedded from an EPS file such that the black parts of the image are displayed at 50% value?

I have a monochrome EPS file which looks like this:

This image is embedded into a Postscript file, which then draws it.  When drawn, I want the image to print or display such that the black parts of the image are drawn as a 50% gray, like this:

The EPS is embedded into the Postscript using the technique shown in https://stackoverflow.com/a/16405528/238886:
/ImageData
currentfile
<< /Filter /SubFileDecode
   /DecodeParms << /EODString (*EOD*) >>
>> /ReusableStreamDecode filter
[-->PUT YOUR EPS HERE<--]
*EOD*
def

/IDForm
<< /FormType 1
   /BBox [154 321 441 521]
   /Matrix [ 1 0 0 1 0 0]
   /PaintProc
   { pop
       /ostate save def
         /showpage {} def
         /setpagedevice /pop load def
         ImageData 0 setfileposition ImageData cvx exec
       ostate restore
   } bind
>> def

And drawn like this:
gsave
IDForm execform
grestore

Is there anything I can wrap around the execform to cause the black/white image to be printed/displayed at 50% value?

A: It really depends on what operations are used inside the EPS file. You could redefine for example setgray like this:
/setgray_orig /setgray load def
/setgray { 0.9 gt {1.0}{0.5} ifelse setgray_orig  } bind def

and then on exit redefine it like so:
/setgray /setgray_orig load def

Now this depends on setgray being used its possible that your eps is using sethsbcolor, setrgbcolor, setcmykcolor etc. if so then you should wrap those too. Be careful with this stuff.
Please note it is not enough to define all gray as 0.5 since someone might be painting white to fill areas so that has to be accounted for too.
Ammendum: you could also just define the setgray inisde the /ostate save def and ostate restore directives then you don't need to separately unload the functionality.


text:
Q: onCreate и onPostExecute() @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ListView listView=(ListView)findViewById(R.id.listView);
    editText = (EditText)findViewById(R.id.editText);

    ArrayList<String> books=new ArrayList<>();
    ArrayAdapter<String> adapter;
    adapter=new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,books);
    listView.setAdapter(adapter);

    //books.add("NEW NEW NEW"); ЭТО РАБОТАЕТ
    //adapter.notifyDataSetChanged();

    new MyAsyncTask().execute();
}

class MyAsyncTask extends AsyncTask<String, String, String> {
    String a, b, answerHTTP;
    String server = "blabla.net";

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected String doInBackground(String... params) {
        HttpClient httpclient = new DefaultHttpClient();
        HttpGet httpget;
        try {
            httpget = new HttpGet(server + "?req=getList");
            HttpResponse response = httpclient.execute(httpget);

            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity entity = response.getEntity();
                answerHTTP = EntityUtils.toString(entity);
            }
        }
        catch (ClientProtocolException e) {
        }
        catch (IOException e) {
        }
        catch(RuntimeException e){
            System.err.println(e.getMessage());
        }
        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        try {
            JSONObject jo=new JSONObject(answerHTTP);
            JSONArray jsonNames=jo.getJSONArray("names");
            JSONArray jsonAuthors=jo.getJSONArray("authors");

            //editText.setText(jsonNames.getString(0));

            for(int i=0;i<jsonNames.length();i++){
                books.add("New man"); // ЭТО НЕ РАБОТАЕТ
                adapter.notifyDataSetChanged();
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

        super.onPostExecute(result);

    }
}

}
При обращении к books из OnPostExecute выдаёт исключение. А при обращении к books из OnCreate всё правильно отрабатывает.

A: Вы объявили books в onCreate(), его поле видимости остается там же.
Объявите его в теле класса, а инициализируйте в onCreate(), books станет видимым для всех методов:
public class MainActivity extends Activity {

    ArrayList<String> books;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        books=new ArrayList<>();
    }
}


text:
Q: Calling a method with List Ids parameter I need to test a method in Developer console .

*

*Method is public . So I can test from Dev Console , right?

*Since it's a static method , I need to call ClassName.Methodname(Parameters)- This class should be the outermost class or the inner one?

*Method signature is public static List<InnerClassName> methodname(List<String> RecorIds) - Can you please give an example of parameter?

I was calling like:
OuterClassName.methodname(id1,id2);

Can anyone please correct me?

A: Apex has neat collection initialization syntax (for arrays, lists, sets and maps) that allows less verbose code:
innerclassList = OuterClassName.methodname(new List<String>{id1, id2});

Better to use the Id type rather than the String type to make what is going on clearer; using the Id type also makes some useful methods available.
So the call could be:
innerclassList = OuterClassName.methodname(new Id[]{id1, id2});

A: List<InnerClassName> innerclassList = new List<InnerClassName>();
List<String> strList = new List<String>();
strList.add(id1);
strList.add(id2);

innerclassList  =OuterClassName.methodname(strList );

hope this will help..


text:
Q: How to call a method with Context context Hello i found this method that creates a file and add strings in it
public void generateNoteOnSD(Context context, String sFileName, String sBody) {
try {
    File root = new File(Environment.getExternalStorageDirectory(), "Notes");
    if (!root.exists()) {
        root.mkdirs();
    }
    File gpxfile = new File(root, sFileName);
    FileWriter writer = new FileWriter(gpxfile);
    writer.append(sBody);
    writer.flush();
    writer.close();
    Toast.makeText(context, "Saved", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
    e.printStackTrace();
}
}

My question is how to call this method ? i tried something like this
 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    String FILENAME = "hello_file";
    String string = "hello world!";
    generateNoteOnSD(Context ,FILENAME,string);
}

I don't understand the Context context part

A: you need to call the getApplicationContext() if you are in an Activity
generateNoteOnSD(getApplicationContext(),FILENAME,string);

A: use
generateNoteOnSD(YoureActivity.this,FILENAME,string);

A: protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 String FILENAME = "hello_file";
 String string = "hello world!";
 generateNoteOnSD(YourActivityName.this ,FILENAME,string);
}

A: If your using Fragment then do like this
generateNoteOnSD(getContext(),FILENAME,string);

if it is Activity do like this
generateNoteOnSD(YourActivityName.this,FILENAME,string);


text:
Q: How to get a return value from a thread? Lets say a function,
int fun(){
    static int a = 10;
    a = a+1;
    return a;
}

The above function is returning a integer value,
//Without thread obtaining return value
#include<iostream>
int main()
{
    int var = 0;
    var = fun();
    std::cout << "The value " << value << std::endl;
    return 0;
}

Now is there any possible way to get the returned value when invoked by C++11 thread,
//Using thread
#include<iostream>
#include<thread>
int main()
{
    std::thread t1(fun);//Invoking thread
    //How to obtain the return value of the thread ?
    return 0;
}

Thanks!

A: For obtaining return values form functions that are meant to be run in background, you may want to consider std::future instead of directly creating an std::thread object. You can use the std::async() function template to start an asynchronous task. It returns an std::future object that will eventually contain the return value of the function passed:
auto res = std::async(fun);

// ... optionally do something else

std::cout << res.get() << '\n';

That is, you create an std::future<int> by calling std::async(func). Then, when you need fun()'s return value, you simply call the get() member function on the future. If the future isn't ready yet (i.e., if it doesn't have the result yet), then the thread will block until it is.

Why not directly use std::thread
The problem with std::thread is that it doesn't provide a direct mechanism for transferring the return value of the callable passed at its construction. For example, suppose you want to start a new thread with std::thread to calculate the sum of two integers with the following function:
int sum(int a, int b) { return a + b; }

What you would probably try is:
std::thread th_sum(sum, 1, 2);

// ... optionally do something else

th_sum.join();
// calculation is finished, but where is the result?

The thread represented by th_sum does calculate the sum of 1 and 2. However, you don't get sum()'s return value, i.e., the result, from the associated std::thread object.
Instead, what you could do to handle this deficiency is, for example, to create a wrapper function for sum() that has an out parameter for the result instead of returning it:
void sum_outparam(int a, int b, int& res) { res = sum(a, b); }

Then, you can start a new thread for running this wrapper function and with help of std::ref() you will obtain the result in res:
int res;
std::thread th_sum(sum_outparam, 1, 2, std::ref(res));

// ... optionally do something else

th_sum.join();
// now, res contains the result

A: You can use async, a promised future (pun intended) or packaged task.
// future from a packaged_task
std::packaged_task<int()> task(fun); // wrap the function
std::future<int> f1 = task.get_future();  // get a future
std::thread(std::move(task)).detach(); // launch on a thread

// future from an async()
std::future<int> f2 = std::async(std::launch::async, fun);

// future from a promise
std::promise<int> p;
std::future<int> f3 = p.get_future();
std::thread( [](std::promise<int>& p){ p.set_value(fun()); },
             std::ref(p) ).detach();

std::cout << "Waiting...";
f1.wait();
f2.wait();
f3.wait();
std::cout << "Done!\nResults are: "
          << f1.get() << ' ' << f2.get() << ' ' << f3.get() << '\n';

A: No, std::thread is just a simple C++ wrapper that allows to start an OS thread of execution and wait until it's done.
To share the return value with the calling thread, you can either manually provide the thread with a shared state, or use a higher-level facilities like packaged_task, future etc.


text:
Q: If x is in the derived algebra, show that Tr(ad a)=0 Let $L$ be a Lie algebra, and let $a\in [L,L]$. How to prove that $trace(ad_a)=0$?

A: Hint: If $x=[a,b]$, Jacobi implies that $ad_x=ad_a(ad_b)-ad_b(ad_a)$. Since $trace(fg)=trace(gf)$ the result follows.


text:
Q: Is performance hit hard when you reinitialize a subscription in sql server 2005 I haven't worked with reinitializing a subscription for SQL Server 2005 replication before and the time has come. I've added a few new articles and need to push those down to the subscriber. Before I reinitialize, which I've read is what I want to do, I want to have a feel for potential performance hit when I kick it off. My gut says that all should be fine but I'd appreciate any experience you have.
The goods:
-Publishing db server is big, fast, with loads of RAM and running enterprise.
-The subscription covers numerous tables with good amounts of data (30 GB) but the new articles are super small.
Thanks

A: BTW - There was not a performance hit.


text:
Q: Cite Command with a Customised Field for Biblatex I am writing a PhD and my mentor wants me to use a specific short form of citation in the footnotes and long one in the bibliography at the end of the work. So basically I need to have three short fields instead of classical two (shorttitle and shortauthor).
I need to find a way to add shortseries which I would use in footnotes.
This is what I use so far for the two fields:
\DeclareBibliographyDriver{myshort}{%
    \usebibmacro{begentry}%
    \ifboolexpr{ test{\ifnameundef{shortauthor}}
                or test {\iffieldundef{shorttitle}}}
      {\usedriver{}{\thefield{entrytype}}}
      {\printnames{shortauthor}%
       \setunit{\addcomma\space}%
       \printfield{shorttitle}\isdot}%
       \usebibmacro{finentry}%
    }
\DeclareCiteCommand{\mycite}[\mkbibfootnote]
  {\usebibmacro{prenote}}
  {\usedriver{}{myshort}}
  {\multicitedelim}
  {\usebibmacro{postnote}}

This is what this produces:

See Iust., De Triph. S. 11.

I need to either find a way to introduce another bibliography field which would be called shortseries or I need to find a way to use some of the optional fields in the incollection like note which I never use to take over this function.
Here is my MWE:
    \documentclass[a4paper,11pt]{scrartcl}
    \usepackage[latin1]{inputenc}
    \usepackage{csquotes}
    \usepackage{blindtext}
    \usepackage{filecontents}
    \begin{filecontents}{\jobname.bib}
     @incollection{iustinus1997,
            Address = {Berlin/New York},
            Author = {{Iustinus Martyr}},
            Title = {Iustini Martyris dialogus cum Tryphone},
            Editor = {Miroslav Marcovich},
            Publisher = {Walter de Gruyter},
            Series = {Patrologiae cursus completus: Series Graeca},
            Shortauthor = {Iust.},
            Shorttitle = {De Tryph.},
            Shortseries = {PG},
            Volume = {47},
            Year = {1997}}
    \end{filecontents}
    \usepackage[ngerman]{babel}
\usepackage[style=historische-zeitschrift, maxnames=2, hyperref=true, backref=true, backrefstyle=none, backend=bibtex,idemtracker=true]{biblatex}
    \bibliography{\jobname}
    \DeclareBibliographyDriver{myshort}{%
        \usebibmacro{begentry}%
        \ifboolexpr{ test{\ifnameundef{shortauthor}}
                    or test {\iffieldundef{shorttitle}}}
          {\usedriver{}{\thefield{entrytype}}}
          {\printnames{shortauthor}%
           \setunit{\addcomma\space}%
           \printfield{shorttitle}\isdot}%
           \usebibmacro{finentry}%
        }
    \DeclareCiteCommand{\mycite}[\mkbibfootnote]
      {\usebibmacro{prenote}}
      {\usedriver{}{myshort}}
      {\multicitedelim}
      {\usebibmacro{postnote}}
    \begin{document}
    \blindtext \mycite[See][S. 11]{iustinus1997}
    \blindtext
    \printbibliography

    \end{document}

and when i use: \mycite[See][11]{iustinus1997} this is what I need to get as an end-result:

See Iust., De Tryph., in: PG 47, S. 11.

Anyone got the idea how I can achieve this? Thanks in advance for your answers!

A: The easiest way to do this would be to use one of the user fields. Let's say usera.
The following is essentially the code posted above, but using usera rather than shortseries:
\documentclass[a4paper,11pt]{scrartcl}
\usepackage[latin1]{inputenc}
\usepackage{csquotes}
\usepackage{blindtext}
\usepackage{filecontents}
\begin{filecontents}{\jobname.bib}
 @incollection{iustinus1997,
        Address = {Berlin/New York},
        Author = {{Iustinus Martyr}},
        Title = {Iustini Martyris dialogus cum Tryphone},
        Editor = {Miroslav Marcovich},
        Publisher = {Walter de Gruyter},
        Series = {Patrologiae cursus completus: Series Graeca},
        Shortauthor = {Iust.},
        Shorttitle = {De Tryph.},
        Usera = {PG},
        Volume = {47},
        Year = {1997}}
\end{filecontents}
\usepackage[ngerman]{babel}
\usepackage[style=authoryear, hyperref=true]{biblatex}
\bibliography{\jobname}
\DeclareBibliographyDriver{myshort}{%
    \usebibmacro{begentry}%
    \ifboolexpr{ test{\ifnameundef{shortauthor}}
                or test {\iffieldundef{shorttitle}}}
      {\usedriver{}{\thefield{entrytype}}}
      {\printnames{shortauthor}%
       \setunit{\addcomma\space}%
       \printfield{shorttitle}\isdot}%
       \iffieldundef{usera}
         {}
         {\setunit{\addcomma\space}% or \newunit
          \usebibmacro{in:}%
          \printfield{usera}%
          \setunit*{\addspace}%
          \printfield[default]{volume}}% or \printfield{volume}
       \usebibmacro{finentry}%
    }
\DeclareFieldFormat{usera}{#1}
\DeclareCiteCommand{\mycite}[\mkbibfootnote]
  {\usebibmacro{prenote}}
  {\usedriver{}{myshort}}
  {\multicitedelim}
  {\usebibmacro{postnote}}
\begin{document}
\blindtext \mycite[See][S. 11]{iustinus1997}
\blindtext
\printbibliography

\end{document}

Which produces

This should also work (1) If there is no "Usera" field, and (2) if there is no volume number. A variation would be to use the "usual" way of writing volumes, which I have suppressed, and to have a period (rather than a comma) before the "in:". I've shown this code in comments, above. If we replace those lines we get.

By all means play around with the driver to get things to your liking. Be careful not to introduce stray spaces, which are the most common source of infuriation in driver-writing. If in doubt, comment the end of every line.
You could use your "shortseries" field if you wanted to using a source mapping, but it's probably overkill.


text:
Q: How do I specify a spacing constraint as a proportion of the superview's size? Say I have an image view and I want its width to be equal to half of the superview's width. I can add an "Equals Width" constraint between the image view and the superview, using a multiplier of 0.5.
Similarly, I'm looking for a way to specify a spacing constraint as a proportion of the superview's size. Continuing with the example above, instead of wanting the width of the image view to be half of the superview's, I would, for instance, want the distance between the bottom of my image view and the bottom layout guide to be a fifth of the superview's height.

A: Here is one solution that has worked for me in the past. It feels like a bit of an odd way to do it, but it will do the trick.
First, put five hidden views in your superview that are of equal heights. Be sure to use constraints to make these expand and contract with their superview. Now no matter what size your superview is, you will have these views inside of it that are exactly one fifth of your superview's size.

To use the example from your question, now you can constrain your imageView's size to be proportional to one of those five hidden views. Then you can constrain it to be centered to one of them so your spacing will also be appropriate for any size.


text:
Q: Error con un if múltiple

#include <iostream>
using namespace std;

int main(){
    int num1;
    cout<<"Ingrese un numero: ";
    cin>>num1;
    if (num1>0 && num1<100) {
        num1%10==4;
        cout<<"El numero termina en 4.";
    }
    else if (num1>100 && num1<1000) {
        num1%100==4;
        cout<<"El numero termina en 4. ";
    }
    else if (num1>1000 && num1<10000) {
        num1%1000==4;
        cout<<"El numero termina en 4.";
    }
    else{
            (cout<<"El numero no termina en cuatro.");
    }

    return 0;
}

Soy novato, buenas tardes.
Necesito que este programa me diga si un número cualquiera termina en cuatro (4) o no, el problema es que independiente del último dígito siempre me dice que termina en cuatro (4). En qué estoy fallando?

A: num1%100==4;
cout<<"El numero termina en 4.";

Esta expresión compara num%100 con 4 y devuelve true o false, pero no hace nada con ese valor. Si lo que quieres es que haga algo, lo tienes que poner dentro de un if
if (num1%10==4) {
  cout<<"El numero termina en 4.";
}

o, teniendo encuenta el resto de tu código
if (num1>0 && num1<100 && num1%10==4) {

Luego está la cuestión de que no entiendes muy bien qué hace el operador módulo. Para sacar el digito menos significativo siempre se hace %10, no importa lo grande que sea el dividendo. Para que lo entiendas, %10 te dará un número entre 0 y 9, %100 un número entre 0 y 99, %1000 un número entre 0 y 999....
Por ejemplo, al hacer 4124%1000 obtienes 124, que obviamente no es igual a 4.
Es decir, no necesitas tantos if y tantos casos especiales. Sólo una operación de módulo, una comparación, y un if.

A: Buen día
En tu código solo estas evaluando rango:
if (num1>0 && num1<N)

dentro de eso a continuación tienes:
num1%10==4;

lo anterior no lo estas evaluando (alguna sentencia selectiva); y la instrucción que tienes seguido es imprirmi a pantalla en mensaje siempre con:
cout<<"El numero termina en 4.";

te falta evaluar; si la intención de tu código la entiendo debe ser:
if ((num1%10)==4) /* Esto para el primer "if (num1>0 && num1<100)" completa los demás según corresponda */
    cout<<"El numero termina en 4.";

A: felicidades vas muy bien, solo que dentro de los if o los if-else debes de meter otro if, para poder hacer la comparación y verificar si termina en 4 entonces:
num1%10==4;

debería quedar como
if(num1%10==4)
{ cout << "El numero termina en 4"}
else
{ cout << "El numero NO termina en 4"}

Otra cosa, si haces el modulo "%" sobre 10 directamente no necesitas ir haciendo tantos casos, ni haces tan redundante tu código;
24984 % 10 = 4
24983 % 10 != 4