text:
Q: webservice authorization best practices I'm creating a webpage which is linked to a web service i am creating.
now the webpage is easy. i can create a session to store login information which gets passed to the webservice with my jquery url calls to the webservice.
but how would this be done if its a different website on a different domain accessing my webservice (client side access via javascript ajax) ?
would it call my webservice/login?userid=&password= which returns a sessionID
then that website has to remember the sessionID and include it on every call?
example: order/outbound/create?address=&item=&companyName=&sessionID=435hg34kh
?
I appreciate any help i could receive on this topic.
not that this really has anything to do with the above question (I think) i'm programming the webservice in php.

A: Authentication with webservices depends either on the HTTP/Soap protocols, either in the service contract (generally using a token).
The solution based on a first call retrieving an ID and then exchanging session id is the good one for client side invocation (that have no access to HTTP/Soap protocols, only services parameters, in such case you're generally using light Webservices based on Rest).
Business side invocation may also rely on Basic Authentication or WS-Security. Ebay is using your approach for its webservices, that are generally invoked from business applications (and not directly client browser).
One consequence is that effectively the server and the client need to maintains the session token. You eventually need an invalidation service that logout the user (preventing from the login token from beeing reused).
Basic approach for cross domain Javascript HTTP invocation is documented here


text:
Q: How do I show my closest 3 competitors on a map? I work for a retailer and would like to create a map in Power BI for all of our stores and their 3 closest competitors, like the example below (Ideal Output). The blue dot is our store and the red dots are our competitors. Ideally, the map would change automatically when a different store is selected in a drop-down slicer. Please see the example data below (My Data).
Thanks,
Mark
Ideal Output:

My Data

Table 1: All of our stores. Very basic. Every store has its own unique number, along with basic store details including geocodes.
Table 2: All competitors. Every competitor has a unique number along with basic information including geocodes.
Table 3: Our stores and their 3 closest competitors.

A: Here's the solution that comes to mind for me. Create a new table that combines information from all 3 of the tables provided. It will be formatted like your Table 1 or Table 2, but with two new columns, Type and Slicer Store.
Type will specify whether the row is your own store or a competitor. Slicer Store will specify which rows should be displayed when that store's name is selected in the dropdown slicer.
Each row from your Table 3 will have 4 rows in the new table, one for each of the columns. The Slicer Store column in your new table will contain the Store Number from each row in Table 3. The Type column in your new table is self-explanatory.
You will end up with something like the following.

Number
Name
Address
Latitude
Longitude
Type
Slicer Store

JL123
...
...
...
...
Store
JL123

C1
...
...
...
...
Competitor
JL123

C2
...
...
...
...
Competitor
JL123

C3
...
...
...
...
Competitor
JL123

JL456
...
...
...
...
Store
JL456

C2
...
...
...
...
Competitor
JL456

C3
...
...
...
...
Competitor
JL456

C4
...
...
...
...
Competitor
JL456

Now for how to use it in Power BI. Create a single-select dropdown slicer using your new Slicer Store column. Then create your map visual using the rows in your new table. Use your new Type column as the Legend/Category. This allows you to color stores vs competitors differently in the visual.
Bing bang boom, you're done. Note that you may have "duplicate" rows for competitors in your new table. For example, if JL123 and JL456 were physically located right next to each other, then rows for C1, C2, and C3 would each appear twice in your new table. The Slicer Store would be different (JL123 or JL456) for these rows, though.
How you create the new table, either manually or with some sort of script, is the hard part.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to render a partial in sinatra view (haml in haml)? I have a simple sinatra app that uses haml and sass for the views. One of the views (located in the views folder) is a partial for my navigation menu. I am trying to render it from index.haml but I get the following error: wrong number of arguments (1 for 2)
I am trying to render it with the following lines in index.haml
.navigation
  = render :partial => "nav"

A: Here's how I do it (more simply than @kfl62's answer, more feature-rich than @jm3's answer):
module Partials
  def partial( page, variables={} )
    haml page.to_sym, {layout:false}, variables
  end
end
helpers Partials

Use it in your Haml file like:
%ul#comments
  - @comments.each do |comment|
    %li= partial :comment, comment:comment

A: EDIT: !!! OUTDATED !!! Read Jason's answer below!
What are you trying works in rails! Sinatra has no partial method. An implementation of partial on Sinatra looks like  this (source gist) from github:
module Haml
  module Helpers
    def partial(template, *args)
      template_array = template.to_s.split('/')
      template = template_array[0..-2].join('/') + "/_#{template_array[-1]}"
      options = args.last.is_a?(Hash) ? args.pop : {}
      options.merge!(:layout => false)
      if collection = options.delete(:collection) then
        collection.inject([]) do |buffer, member|
          buffer << haml(:"#{template}", options.merge(:layout =>
          false, :locals => {template_array[-1].to_sym => member}))
        end.join("\n")
      else
        haml(:"#{template}", options)
      end
    end
  end
end

Including this method, you may call partial in your .haml files, like
= partial("partial_name")
If you want to render a view in an other view syntax is
= render(:haml,:'rel_path_to_view',:locals => {:optional => option})
Notice the syntax differences between rails and sinatra regarding render method!

A: You can just use Sinatra's haml function:
= haml :nav

A: Or you could just do this:
helpers do
  def partial(page, options={})
    haml page.to_sym, options.merge!(:layout => false)
  end
end

And include your partial with:
= partial( "something-rad" )


text:
Q: How to Return to App on Notification Click I am showing a notification in Android. This is working fine. Now I want to focus MyApp if the User clicks on the Notification. I know I can pass an Intent to the Notification, so I could start any Activity I want. But I do not wont to start a specific activity, I just want to go back into the app. And if the App is not running then I want to start the app normally and also not a specific Activity.
So those three scenarios:
A: MyApp is running in background, but does not have focus
-> Focus MyApp
B: MyApp is not running
-> Start MyApp normally
C: MyApp is running and also has focus
-> Do nothing
My Code for the Notification:
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, channelId)
            .setContentTitle(title)
            .setContentIntent(intent) // -> here I could parse an Intent, I know...
                                      //    But that is not exactly what I want

I found nothing on Google for that. Is that possible?

A: Try this as pending intent:
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, resultIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);

This will :

*

*If app not running, start the app.

*If in foreground, will do nothing, focus again to the app.

*If in background, (most probably, as far as I can recall) will focus the app and will not create activity if already created.


text:
Q: Alternate object instead of using an enum for index values My below code works fine, however, I would like to try and improve its portability. The priceLevels index numbers are subject to change, so instead of me having to update the program, I would like to have a settings option to set those index numbers.
I also want to be able to control the ToString() method for the PriceLevel class.
The PriceLevel class will be a part of my Customers class, so my usage would be something like:
if(someOtherVariable == thisCustomer.priceLevel) //do some stuff

someString = thisCustomer.priceLevel.ToString()

-
public enum priceLevels
{
    SELECT = 2,
    PLUS = 3,
    PREMIER = 3,
    EFI = 4,
    MSELECT = 5,
    SPECIAL = 6
}

class PriceLevel
{
    public priceLevels priceLevel { get; set; }

    public override string ToString()
    {
        string myString = "No Level Set";

        if (priceLevel == priceLevels.SELECT) return "Partner-Select";
        if (priceLevel == priceLevels.PLUS) return "Plus/Premier";
        if (priceLevel == priceLevels.PREMIER) return "Plus/Premier";
        if (priceLevel == priceLevels.EFI) return "eFi Plus-SPA";
        if (priceLevel == priceLevels.MSELECT) return "mSelect";
        if (priceLevel == priceLevels.SPECIAL) return "Special";

        return myString;
    }
}

Would anyone be able to suggest an alternate object that I can use in place of the priceLevels enum?

A: I don't know if you use priceLevels for something else. because if you change PriceLevel class or remove the priceLevels enum, meybe you need to change Customer class too or the way how to save the price level value.
If you keep priceLevels enum. You can use a attibute description for this and include in your project a simple extension:
public enum priceLevels
{
    [Description("Partner-Select")]
    SELECT = 2,
    [Description("...")]
    PLUS = 3,
    [Description("...")]
    PREMIER = 3,
    [Description("...")]
    EFI = 4,
    [Description("...")]
    MSELECT = 5,
    [Description("...")]
    SPECIAL = 6
}

public static string GetDescription(this Enum enumValue)
{
    var fi = enumValue.GetType().GetField(enumValue.ToString());

    var attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);

    return (attributes != null && attributes.Length > 0)
                ? attributes[0].Description
                : enumValue.ToString();
}

Use:
someString = thisCustomer.priceLevel.priceLevel.GetDescription()

or you can change your Customer class and include in this a property PriceLevel with the type priceLevels:
 someString = thisCustomer.PriceLevel.GetDescription()

When I use this, somethimes I include a resource file. because I can save muy description in this resouce.

A: If the main reason not to use Enum is the ToString(), you can override the result by adding an attribute on the members and using an extension method as @andres suggested; if you want a more complex structure, you can simulate an enum and add functionalities:
public struct PriceLevels
{
    public static PriceLevels NONE = 0;

    public static PriceLevels SELECT = 2;
    public static PriceLevels PLUS = 3;
    public static PriceLevels PREMIER = 3;
    public static PriceLevels EFI = 4;
    public static PriceLevels MSELECT = 5;
    public static PriceLevels SPECIAL = 6;

    public bool Equals(PriceLevels other) => _number == other._number;

    public override bool Equals(object obj) => !ReferenceEquals(null, obj) && obj is PriceLevels && Equals((PriceLevels) obj);

    public override int GetHashCode() => _number;

    readonly int _number;

    PriceLevels(int number)
    {
        _number = number;
    }

    public static implicit operator PriceLevels(int number) => new PriceLevels(number);

    public static bool operator ==(PriceLevels leftLevel, PriceLevels rightLevel) => leftLevel._number == rightLevel._number;

    public static bool operator !=(PriceLevels leftLevel, PriceLevels rightLevel) => !(leftLevel == rightLevel);

    public override string ToString()
    {
        if (this == SELECT) return "Partner-Select";
        if (this == PLUS) return "Plus/Premier";
        if (this == PREMIER) return "Plus/Premier";
        if (this == EFI) return "eFi Plus-SPA";
        if (this == MSELECT) return "mSelect";
        if (this == SPECIAL) return "Special";

        return "No Level Set";
    }
}


text:
Q: What is the difference when using Output Buffer on PHP? I am new at PHP, and I have a question about Output Buffering.I have this code I found on the net:
ob_start();
system('ipconfig /all');
$contents = ob_get_contents();
ob_end_clean();
$searchFor = "Physical";
$pmac = strpos($contents, $searchFor);
$mac = substr($contents, ($pmac + 36), 17);
return $mac;

It all works fine, but I don't understand the usage of the output buffer here.If I change it to:
$contents = system('ipconfig /all');
$searchFor = "Physical";
$pmac = strpos($contents, $searchFor);
$mac = substr($contents, ($pmac + 36), 17);
return $mac;

It can't seem to filter the contents of $contents to find the mac address.So what does output buffering do for this?
From what I understand about output buffering, it loads all of the page into a single variable, then returns it all at once so the page loads all at once and faster.I can't really see how this would change the output so drastically in this situation.

A: The system() call will not just run a command, but also display the output. At the very least your sample code should have assigned the return value instead.
Output buffering is furthermore needed, as the system call will flush the command results directly to the webserver (unless there's an explicit output buffer).
What simply should have been used here instead is exec() - with assigning the result to & $contents right away.


text:
Q: creating powershell script to backup a file and append the date Currently I have a one line batch file to back up a file.  I run it manually when I need to back up a file.  The only thing I would like to add to it is the current date.  Here is what I have:
xcopy /W /Y ACTIVE.DB ACTIVE.DB.BACKUP
the destination file should simply be ACTIVE.DB.BACKUP.YYYYMMDD.  How would I go about creating a script that will allow me to double click on it from Windows Explorer and make the xcopy happen?

A: You can customize your filename by embedding a formatted [datetime]::now in the file name in PowerShell like so:
xcopy /W /Y ACTIVE.DB "ACTIVE.DB.BACKUP.$([datetime]::now.ToString('yyyy-MM-dd'))"

If the line feels busy and unmaintainable, you can refactor it to multiple lines:
$now = [datetime]::now.ToString('yyyy-MM-dd')
xcopy /W /Y ACTIVE.DB "ACTIVE.DB.BACKUP.$now"

To get double-click execution, I usually make a batch file that runs the PowerShell command as described here:
Set up PowerShell Script for Automatic Execution

A: Just to point out that you can do this with Copy-Item e.g.:
Set-Location $path
Copy-Item ACTIVE.DB "ACTIVE.DB.$(get-date -f yyyyMMdd)" -Force -Confirm

If you're going for robust then I'd use robocopy.exe.

A: I just made a Daily/Weekly/Monthly/Quarterly/Yearly backup script in Powershell this month, and hope it helps.
This DWMQY backup scenario is to zip a source folder to a date-named zip file, then keep the zips of:

*

*last 7 days

*4 weeks (each Friday's)

*6 months (the last Friday's of each month)

*4 quarters (the last month's of quarter)

*2 years (the last quarter's of year).

Running as scheduled task on daily basis, it puts the zips into a target folder which is also a Microsoft OneDrive's local folder, so the zips also being remotely sync'd to OneDrive server. Those outdated (non-Friday daily or non-last-DWMQY) zips will be moved to a non-remotely-sync'd folder.
It's March 5, 2016 today, the following zips should be in the target folder:

*

*7 days: 160304-160229-160227

*4 weeks: 160304, 160226, 160219,160212

*6 months: 160226, 160129, 161225, 151127, 151025, 150925

*4 quarters: 151225, 150925,150626,150327

*2 years: 151225, 141226

So there will be 23 zips (actually less since the dups among DWMQY), our files are 250 text documents which is 0.4 GB after zipping, so it's 23*0.4 = 9.2 GB in total, which is less than OneDrive free 15 GB quota.
For large source data, 7-zip can be used, which provides maximum 16 mil TB zip size. For directly backup folders instead of zips, haven't tried. Guessing it's a transferable procedure from the current zip way.

# Note: there are following paths:
# 1. source path: path to be backed up.
# 2. target path: current zips stored at, which is also a remote-sync pair's local path.
# 3. moved-to path: outdated zips to be moved in this non-sync'able location.
# 4. temp path: to copy the source file in to avoid zip.exe failing of compressing them if they are occupied by some other process.
# Function declaration
. C:\Source\zipSaveDated\Functions.ps1
# <1> Zip data
$sourcePath = '\\remoteMachine1\c$\SourceDocs\*'
$TempStorage = 'C:\Source\TempStorage'
$enddate = (Get-Date).tostring("yyyyMMdd")
$zipFilename = '\\remoteMachine2\d$\DailyBackupRemote\OneDrive\DailyBackupRemote_OneDrive\' + $enddate + '_CompanyDoc.zip'
Remove-Item ($TempStorage + '\*') -recurse -Force
Copy-Item $sourcePath $TempStorage -recurse -Force

Add-Type -A System.IO.Compression.FileSystem
[IO.Compression.ZipFile]::CreateFromDirectory($TempStorage, $zipFilename)

# <2> Move old files
$SourceDir = "\\remoteMachine2\d$\DailyBackupRemote\OneDrive\DailyBackupRemote_OneDrive"
$DestinationDir = "\\remoteMachine2\d$\DailyBackupRemote\bak" # to store files moved out of the working folder (OneDrive)
$KeepDays = 7
$KeepWeeks = 4
$KeepMonths = 6
$KeepQuarters = 4
$KeepYears = 2
# <2.1>: Loop files
$Directory = $DestinationDir
if (!(Test-Path $Directory))
{
    New-Item $directory -type directory -Force
}
$files = get-childitem $SourceDir *.*
foreach ($file in $files)
{ # L1
    # daily removal will not remove weekly copy, 7
    If($file.LastWriteTime -lt (Get-Date).adddays(-$KeepDays).date  `
        -and $file.LastWriteTime.DayOfWeek -NotMatch "Friday"  `
        )
        {
        Move-Item $file.fullname $Directory -force
        }
} # L1 >>
$files = get-childitem $SourceDir *.*
foreach ($file in $files)
{ # L1
    # weekly removal will not remove monthly copy, 4
    If($file.LastWriteTime -lt (Get-Date).adddays(-$KeepWeeks * 7).date  `
        -and (Get-LastFridayOfMonth ($file.LastWriteTime)).Date.ToString("yyyyMMdd") -NotMatch $file.LastWriteTime.Date.ToString("yyyyMMdd")
        )
        {
        Move-Item $file.fullname $Directory -force
        }
} # L1 >>
$files = get-childitem $SourceDir *.*
foreach ($file in $files)
{ # L1
    # monthly removal will not remove quarterly copy, 6
    If($file.LastWriteTime.Month -lt ((Get-Date).Year - $file.LastWriteTime.Year) * 12 + (Get-Date).Month - $KeepMonths `
        -and $file.LastWriteTime.Month -NotIn 3, 6, 9, 12
        )
        {
        Move-Item $file.fullname $Directory -force
        }
} # L1 >>
$files = get-childitem $SourceDir *.*
foreach ($file in $files)
{ # L1
    # quarterly removal will not remove yearly copy, 4
    If($file.LastWriteTime.Month -lt ( (Get-Date).Year - $file.LastWriteTime.Year) * 12 + (Get-Date).Month - $KeepQuarters * 3 `
        -and $file.LastWriteTime.Month -NotIn 12
        )
        {
        Move-Item $file.fullname $Directory -force
        }
} # L1 >>
$files = get-childitem $SourceDir *.*
foreach ($file in $files)
{ # L1
    # yearly removal will just go straight ahead. 2
    If($file.LastWriteTime.Year -lt (Get-Date).Year - $KeepYears )
        {
        Move-Item $file.fullname $Directory -force
        }
} # L1 >>

<Functions.ps1>
function Get-TimesResult3
    {
    Param ([int]$a,[int]$b)
    $c = $a * $b
    Write-Output $c
    }

function Get-Weekday {
    param(
        $Month = $(Get-Date -format 'MM'),
        $Year = $(Get-Date -format 'yyyy'),
        $Days = 1..5
    )
$MaxDays = [System.DateTime]::DaysInMonth($Year, $Month)
1..$MaxDays | ForEach-Object {
        Get-Date -day $_ -Month $Month -Year $Year |
          Where-Object { $Days -contains $_.DayOfWeek }
    }
}

function Get-LastFridayOfMonth([DateTime] $d) {
    $lastDay = new-object DateTime($d.Year, $d.Month, [DateTime]::DaysInMonth($d.Year, $d.Month))
    $diff = ([int] [DayOfWeek]::Friday) - ([int] $lastDay.DayOfWeek)

    if ($diff -ge 0) {
        return $lastDay.AddDays(- (7-$diff))
    }
    else {
        return $lastDay.AddDays($diff)
    }
}


text:
Q: Iteration over a list in a Pandas DataFrame column I have a dataframe df as this one:
                                                  my_list
Index
0                                               [81310, 81800]
1                                                      [82160]
2            [75001, 75002, 75003, 75004, 75005, 75006, 750...
3                                                      [95190]
4                                               [38170, 38180]
5                                                      [95240]
6                                                      [71150]
7                                                      [62520]

I have a list named code with at least one element.
code = ['75008', '75015']

I want to create another column in my DataFrame named my_min, containing the minimum absolute difference between each element of the list code and the list from df.my_list.
Here are the commands I tried :
df.loc[:, 'my_list'] = min([abs(int(x)-int(y)) for x in code for y in df.loc[:, 'my_list'].str[:]])
>>> TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'

#or

df.loc[:, 'my_list'] = min([abs(int(x)-int(y)) for x in code for y in df.loc[:, 'my_list']])
>>> TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'

#or

df.loc[:, 'my_list'] = min([abs(int(x)-int(y)) for x in code for y in df.loc[:, 'my_list'].tolist()])
>>> TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'

#or

df.loc[:, 'my_list'] = min([abs(int(x)-int(y)) for x in code for y in z for z in df.loc[:, 'my_list'].str[:]])
>>> UnboundLocalError: local variable 'z' referenced before assignment

#or

df.loc[:, 'my_list'] = min([abs(int(x)-int(y)) for x in code for y in z for z in df.loc[:, 'my_list']])
>>> UnboundLocalError: local variable 'z' referenced before assignment

#or

df.loc[:, 'my_list'] = min([abs(int(x)-int(y)) for x in code for y in z for z in df.loc[:, 'my_list'].tolist()])
>>> UnboundLocalError: local variable 'z' referenced before assignment

A: Write a helper: def find_min(lst): -- it is clear you know how to do that. The helper will consult a global named code.
Then apply it:
df['my_min'] = df.my_list.apply(find_min)

The advantage of breaking out a helper
is you can write separate unit tests for it.
If you prefer to avoid globals,
you will find partial quite helpful.
https://docs.python.org/3/library/functools.html#functools.partial

A: you could do this with a list comprehension:
import pandas as pd
import numpy as np
df = pd.DataFrame({'my_list':[[81310, 81800],[82160]]})

code = ['75008', '75015']

pd.DataFrame({'my_min':[min([abs(int(i) - j) for i in code for j in x])
              for x in df.my_list]})

returns
   my_min
0    6295
1    7145

You could also use pd.Series.apply instead of the outer list, for example:
df.my_list.apply(lambda x: min([abs(int(i) - j) for i in code for j in x]) )

A: If you have pandas 0.25+ you can use explode and combine with np.min:
# sample data
df = pd.DataFrame({'my_list':
                  [[81310, 81800], [82160], [75001,75002]]})
code = ['75008', '75015']

# concatenate the lists into one series
s = df.my_list.explode()

# convert `code` into np.array
code = np.array(code, dtype=int)

# this is the output series
pd.Series(np.min(np.abs(s.values[:,None] - code),axis=1),
          index=s.index).min(level=0)

Output:
0    6295
1    7145
2       6
dtype: int64


text:
Q: Store calls server but does not return my call to store.load never return to the callback function.
If this store is defined in a grid, the message "loading.." never disappears.
myStore.load({
        callback: function () {
            alert('returned');

        },
        params: {'person':1, 'datePost':calendarPost.getValue()}

    });

No errors are displayed, the server (rails) do its job with no errors.
I already try to add a "failure: function", but it´s not called also.
This is my store definition:
var myStore = Ext.create('Ext.data.Store', {
model: 'App.model.Post',
proxy: {
    type: 'ajax',
    format: 'json',
    url: 'posts/build_posts',
    actionMethods :{
        read   : 'POST'
    }
}
});

This is the (real) data returned from the server:
[
{"chegada":null,"consulta_id":null,"convenio_id":1,"data":"2012-11-13","encaixe":false,"hora":"2000-01-01T08:00:00Z","id":40031,"inicio_consulta":null,"medico_id":1,"observacao":null,"paciente_id":1948,"tipo":1},
/* Took out similiar ones */
{"chegada":null,"consulta_id":null,"convenio_id":null,"data":"2012-11-13","encaixe":false,"hora":"2000-01-01T09:15:00-02:00","id":null,"inicio_consulta":null,"medico_id":null,"observacao":null,"paciente_id":null,"tipo":null},
/* Took out similiar ones */
{"chegada":null,"consulta_id":null,"convenio_id":52,"data":"2012-11-13","encaixe":false,"hora":"2000-01-01T14:00:00Z","id":40042,"inicio_consulta":null,"medico_id":1,"observacao":null,"paciente_id":1732,"tipo":1}
/* And so on.. */
]

and this is my model definition:
Ext.define('App.model.Post',{
    extend: 'Ext.data.Model',
    fields: ['id', 'hora', 'data','chegada','tipo','encaixe','nome','paciente_id','consulta_id','inicio_consulta','convenio_id']
});

A: I got the problem. It was missing a Ext.require('App.model.Post'); in my js file.
No error messages make hard to code.


text:
Q: Yet another Python variable scope question I have the following code:
>>> def f(v=1):
...     def ff():
...             print v
...             v = 2
...     ff()
...
>>> f()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 5, in f
  File "<stdin>", line 3, in ff
UnboundLocalError: local variable 'v' referenced before assignment

I do understand why this message occurs (Python variable scope question), but how can I work with v variable in this case? global v doesn't work in this case.

A: In Python 3.x, you can use nonlocal:
def f(v=1):
    def ff():
        nonlocal v
        print(v)
        v = 2
    ff()

In Python 2.x, there is no easy solution.  A hack is to make v a list:
def f(v=None):
    if v is None:
        v = [1]
    def ff():
        print v[0]
        v[0] = 2
    ff()

A: You haven't passed v to the inner function ff.  It creates its own scope when you declare it.  This should work in python 2.x:
def f(v=1):
  def ff(v=1):
    print v
    v = 2
  ff(v)

But the assignment call to v = 2 would not be persistent in other calls to the function.


text:
Q: NSMutableArray : Message sent to deallocated image I am facing a strange problem concerning NSMutableArray. I searched several similar posts but with no luck.The situation is this :
In my appDelegate I declare an   NSMutableArray property like this :
@property (nonatomic, retain) NSMutableArray *myRequests;

Then in a method of the same class I initialize the array like this :
self.myRequests = [[[NSMutableArray alloc] init] autorelease];

Then in a for loop of the same method I add objects to the array:
while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
    MyRequest *req = [MyRequest alloc];

    req.s_prp= [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
   .
   .
   .
  [self.myRequests addObject:req];

  [req release];
}

I use this array to feed a uitableview with data.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

 // Cell initialization ...

    MyRequest *req = (MyRequest *) [delegate.myRequests objectAtIndex:indexPath.row] ;
    cell.stypeLabel.text = req.ser_type_name; // RANDOMLY OCCURING ERROR !!!!!!!!!!!
}

The exception occurs randomly and the message says : [MyRequest ser_type_name]: message sent to deallocated instance 0x6e7af20
Is there anything wrong with the above code ?? MyRequest is a custom class. I am using a custom tableviewcell class.
MyRequest class is quite simple. It has several properties in the form
@property (retain,nonatomic)    NSString *ser_type_name;

and a dealloc method that releases the objects.
Thanks

A: This line is incorrect:
MyRequest *req = [MyRequest alloc];

It should be:
MyRequest *req = [[MyRequest alloc] init];

There could be other errors, but that one is very glaring.

A: You don't show how MyRequest and its properties/ivars are defined, not are you showing how req.ser_type_name is set in your code. Depending on whether they are retained or not, you could be seeing some strange behavior because NSString's stringWithUTF8String returns an autoreleased string. You should check that and fix it if necessary (although I can't see how an error there would give you the message you are reporting)


text:
Q: Нормально ли задавать высоты тегам  и ? Я ученик.
Cтолкнулся с неадекватным поведением в адаптивного элемента (в Хроме в режиме имитации смартфона). Вкратце, проблема видна, когда у его предка стоит правило height: 100vh;, если же вместо этого поставить ему и  и  высоты 100% - всё становится хорошо. В файрфоксе проблемы вовсе не вижу.
Это вообще нормально - ставить какую-либо высоту для  и ?

A: Да, и для html и для body тоже можно задавать разные css-правила, и высоту в том числе.
На будущее, когда возникнут очередные вопросы "А делают ли так в принципе?", подсмотрите ответы на них у профессионалов, например хотя бы здесь:

A: Aleksandr Shemetillo, посмотри мой пример и подумай, почему на данный момент фон не красный? Потом раскомментируй /*height: 100%;*/ и фон станет красным... Но если #wrapper задать height: не в процентах, то он будет виден...  Это я к тому, что изначально у body нет высоты. Хочешь никогда не ошибаться, сделай себе привычку главный файл css начинай с этих строк ниже...
*{
    margin: 0;
    padding: 0;
}

html,
body {
    width: 100%;
    height: 100%;
}

*,
* ::after,
*::before {
  margin: 0;
  padding: 0;
}

html,
body {
  width: 100%;
  /*height: 100%;*/
  background: #272727;
  color: white;
}

#wrapper {
  width: 100%;
  height: 100%;
  background: #f00;
}

A: Это нормально и часто оправдано. Если обратиться к спецификации, то там сказано, что свойство height может быть задано всем элементам за исключением non-replaced инлайновых элементов, ячеек таблиц и column groups.  и  это block-level элементы, так что height можно спокойно им задавать.
Visual formatting model details

'height'
  Applies to:     all elements but non-replaced inline elements, table columns, and column groups


text:
Q: In SQL Server 2014 , how to convert given UTC date time to PST date time, when the server is in UTC How to convert given UTC date time to PST date time, by keeping the daylight stuff in time calculations?
Note that the server I am hitting is in utc. I mean, GETDATE() = GETUTCDATE().
Also, we can't use AT TIME ZONE, as DB is on older SQL Server.
Thanks in advance for the help.

A: Search the site, example: Convert Datetime column from UTC to local time in select statement
Read the link above, also include daylight stuff in there for some of the responses too.


text:
Q: Как правильно дописать замыкание в Python? Есть написанный кусок кода:
Идея такая, в цикле итерировать массив, если найдено совпадение элементов от двух массивов, сформировать новый массив с порядковым индексом n и следующие элементы, которые итерируются в цикле, добавлять в ранее созданный массив coorsinates[n], до следующего совпадения в цикле if.
Сейчас код выдает ошибку вида:
Traceback (most recent call last):
  File "python", line 25, in <module>
TypeError: 'NoneType' object is not callable

По необходимости буду уточнять суть вопроса, если написал недостаточно внятно.


text:
Q: jquery собые по клику на внутренних ссылках Есть див-обертка
внутри куча li div a. это меню. Классы у ссылок разные.
есть ли возможность добавить внутренним ссылкам (тем, что внутри дива-обертки) функцию?
чтобы при клике на любую ссылку внутри дива она срабатывала
вот пример этого меню

 /* див-оберка */

1

2

меню неполное, добавил для примера

A: $(".extra-pb1 a").click(function(e){
  e.preventDefault();
  console.log($(this).attr("href"));
});


text:
Q: Create User Entity from sql data base.Insert data on the textbox I am new in C sharp.I got a project to insert user intity from User_db in SQl.is it write way of code?
is it the write procedure?Though I am getting lots of error.
HTML:
    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="UserEntity.aspx.cs" Inherits="ST_System.RegistarEmployee" %>

    <!DOCTYPE html>

            <form id="form1" runat="server">

<%:DisplayName%>

            <asp:Button ID="Button1" runat="server" Text="タスク一覧" OnClick="Button1_Click" />

            <asp:Button ID="Button2" runat="server" Text="タスク登録" OnClick="Button2_Click" />

            <asp:Button ID="Button3" runat="server" Text="従業員登録" OnClick="Button3_Click" />

            <asp:Button ID="Button4" runat="server" Text="ログアウト" OnClick="Button4_Click" />

            <asp:ValidationSummary ID="ValidationSummary1" runat="server"
                ValidationGroup="Button1" />

                従業員名

                    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
                        ErrorMessage="従業員名を入力してください。"
                        ControlToValidate="TextBox1"
                        ValidationGroup="Button1">※</asp:RequiredFieldValidator>

                ID

                    <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>

                パスワード

                    <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
                    <asp:RegularExpressionValidator ID="RequiredFieldValidator2" runat="server"
                        ErrorMessage="パスワードを入力してください。"
                        ValidationExpression="\d+"
                        ControlToValidate="TextBox3"
                        ValidationGroup="Button1">※</asp:RegularExpressionValidator>

                パスワード(確認)

                    <asp:TextBox ID="TextBox4" runat="server" TextMode="Password"></asp:TextBox>

            <asp:Button ID="Button5" runat="server"
                ValidationGroup="Button5"
                OnClick="Button5_Click" Text="登録" />

        </form>

I tried to insert sql data base value on text box.
This is .CS file.
    using DynamicDll.Db;
    using ST_System.models.Dao;
    using ST_System.models.Entity;
    using System;
    using System.Collections.Generic;
    using System.Data.SqlClient;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;

    namespace ST_System
    {
        public partial class UserEntity : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {
                if (IsPostBack)
                {

                }
                else { }
            }
            public string DisplayName { get; } = "従業員登録";
            public string UserName { get; private set; }
            public string UserId { get; private set; }
            public string Password { get; private set; }

            protected void Button1_Click(object sender, EventArgs e)
            {
                Response.Redirect("Task_View.aspx");
            }
            protected void Button2_Click(object sender, EventArgs e)
            {
                Response.Redirect("Task_Insert.aspx");
            }
            protected void Button3_Click(object sender, EventArgs e)
            {
                Response.Redirect("Employee_Insert.aspx");
            }
            protected void Button4_Click(object sender, EventArgs e)
            {
                Response.Redirect("Logout.aspx");
            }
            protected void Button5_Click(object sender, EventArgs e)
            {
                try
                {
                    using (TranMng mng = TranMng.BeginTransaction("userDB")) { }
                    {

                    }

                    UserEntity userEntity = new UserEntity();
                    userEntity.UserName = Request.Form["TextBox1"];
                    userEntity.UserId = Request.Form["TextBox2"];
                    userEntity.Password = Request.Form["TextBox3"];

                    UserDao userDao = new UserDao();
                    int count = userDao.Insert(userEntity);
                    if (count == 0)
                    {
                        string msg = "この従業員名は利用されています。";
                    }
                    else
                    {

                    }

                    SqlConnection con = new SqlConnection(@"Data Source=localhost;Initial Catalog=task_db;User ID=user2;Password=password");
                    {
                        con.Open();
                        SqlCommand cmd = new SqlCommand("insert into m_user values(@name,@Id,@Password)", con);
                        cmd.Parameters.Add("@name", TextBox1.Text);
                        cmd.Parameters.Add("@Id", TextBox2.Text);
                        cmd.Parameters.Add("@Password", TextBox3.Text);
                        cmd.ExecuteNonQuery();
                        TextBox1.Text = "";
                        TextBox2.Text = "";
                        TextBox3.Text = "";
                        TextBox1.Focus();

                    }

                }
        }
    }

I think the code is not proper.
For user entity do i need only sql part?
is it okay Get,Set?
I have data on sql.I just need to insert data on text box.Though I am new in c sharp,i dont understand how to start.I just created the text box and now planning to insert those data on text box.I cant understand what I need to do?


text:
Q: parsing for PHOAS expressions I think I understand PHOAS (parametric higher-order abstract syntax),
and I see how we can pretty-print an expression (cf. http://www.reddit.com/r/haskell/comments/1mo59h/phoas_for_free_by_edward_kmett/ccbxzoo).
But - I don't see how to build a parser for such expressions, e.g., that takes "(lambda (a) a)" and builds (the Haskell value corresponding to) lam $ \ x -> x. (And it should use Text.Parsec or similar.)
I can build a parser that produces lambda terms with de-Bruijn indexing but what would it help?

A: jozefg has the right answer in his comment.  Always parse to a simple abstract syntax tree, not some clever representation.  Then, after parsing, convert representations.  In this case, it is easy
data Named = NLam String Named | NVar String | NApp Named Named

convert :: (String -> a) -> Named -> Exp a a
convert f (NVar n) = var $ f n
convert f (NApp e1 e2) = app (convert f e1) (convert f e2)
convert f (NLam s e) = lam $ \a -> convert (nf a) e where
  nf a s' = if s' == s then a else f s'

you could of course use something other than a function String -> a as your map.  Data.Map for example would get rid of the linear time lookups.
One cool thing about PHOAS over other HOAS schemes is that you can easily "convert back"
addNames :: ExpF Int (State Int Named) -> State Int Named
addNames (App a b) = liftM2 NApp a b
addNames (Lam f)   = do
  i <- get
  put (i + 1)
  r <- f i
  return $ NLam ('x':show i) r

convert' :: Exp Int Int -> Named
convert' = fst
  . flip runState 0
  . cata addNames
  . liftM (return . NVar . ('x':) . show)

which even works as expected
λ: convert' $ convert undefined $ NLam "x" $ NApp (NVar "x") (NLam "y" (NVar "y"))
> NLam "x0" (NApp (NVar "x0") (NLam "x1" (NVar "x1")))

A: I will again run with the theme of the other answers here and suggest that you parse as though you are just creating the naive representation with named variables. If you want to avoid the intermediate representation, you can kind of inline it into the parser without making it any harder to understand:
data Lam a = Var a | Lam a `App` Lam a | Lam (a -> Lam a)

type MkLam a = (String -> a) -> Lam a

var :: String -> MkLam a
var x = Var . ($ x)

app :: MkLam a -> MkLam a -> MkLam a
app = liftA2 App

lam :: String -> MkLam a -> MkLam a
lam v e env = Lam $ \x -> e $ \v' -> if v == v' then x else env v'

The idea is that instead of using the constructors of your intermediate representation in your parser, you use these functions directly. They have the same types that the constructors would have, so it's really just a drop-in replacement. It's also a bit shorter, since now we don't have to separately write out the ADT and interpreter.

A: As jozefg says, you can easily convert between operations. I'll show how to convert between a named, a de-Bruijn, and a PHOAS representation of lambda terms. It's relatively easy to fuse that into the parser if you absolutely want to, but it's probably better to parse a named representation first and then convert.
Let's assume
import Data.Map (Map)
import qualified Data.Map as M

and the following three representations of lambda terms:
String-based names
data LamN = VarN Name | AppN LamN LamN | AbsN Name LamN
  deriving (Eq, Show)

type Name = String

de-Bruijn indices
data LamB = VarB Int | AppB LamB LamB | AbsB LamB
  deriving (Eq, Show)

PHOAS
data LamP a = VarP a | AppP (LamP a) (LamP a) | AbsP (a -> LamP a)

Now the conversions between LamP and the others (in both directions). Note that these are partial functions. If you're applying them to lambda terms that contain free variables, you're responsible for passing a suitable environment.
How to go from LamN to LamP
Takes an environment mapping names to
PHOAS variables. The environment can be empty for closed terms.
lamNtoP :: LamN -> Map Name a -> LamP a
lamNtoP (VarN n)     env = VarP (env M.! n)
lamNtoP (AppN e1 e2) env = AppP (lamNtoP e1 env) (lamNtoP e2 env)
lamNtoP (AbsN n e)   env = AbsP (\ x -> lamNtoP e (M.insert n x env))

How to go from LamB to LamP
Takes an environment that's a list of
PHOAS variables. Can be the empty list for closed terms.
lamBtoP :: LamB -> [a] -> LamP a
lamBtoP (VarB n)     env = VarP (env !! n)
lamBtoP (AppB e1 e2) env = AppP (lamBtoP e1 env) (lamBtoP e2 env)
lamBtoP (AbsB e)     env = AbsP (\ x -> lamBtoP e (x : env))

How to get from 'LamP' to 'LamN'
Requires potential free variables to
be instantiated to their names. Takes a supply of names for generating
names of binders. Should be instantiated to an infinite list of mutually
different names.
lamPtoN :: LamP Name -> [Name] -> LamN
lamPtoN (VarP n)         _sup  = VarN n
lamPtoN (AppP e1 e2)      sup  = AppN (lamPtoN e1 sup) (lamPtoN e2 sup)
lamPtoN (AbsP f)     (n : sup) = AbsN n (lamPtoN (f n) sup)

How to get from 'LamP' to 'LamB'
Requires potential free variables to
be instantiated to numbers. Takes an offset that indicates the number of
binders we're currently under. Should be instantiated to 0 for a closed
term.
lamPtoB :: LamP Int -> Int -> LamB
lamPtoB (VarP n)     off = VarB (off - n)
lamPtoB (AppP e1 e2) off = AppB (lamPtoB e1 off) (lamPtoB e2 off)
lamPtoB (AbsP f)     off = AbsB (lamPtoB (f (off + 1)) (off + 1))

An example
-- \ x y -> x (\ z -> z x y) y

sample :: LamN
sample = AbsN "x" (AbsN "y"
  (VarN "x" `AppN` (AbsN "z" (VarN "z" `AppN` VarN "x" `AppN` VarN "y"))
            `AppN` (VarN "y")))

Going to de-Bruijn via PHOAS:
ghci> lamPtoB (lamNtoP sample M.empty) 0
AbsB (AbsB (AppB (AppB (VarB 1) (AbsB (AppB (AppB (VarB 0) (VarB 2)) (VarB 1)))) (VarB 0)))

Going back to names via PHOAS:
ghci> lamPtoN (lamNtoP sample M.empty) [ "x" ++ show n | n <- [1..] ]
AbsN "x1" (AbsN "x2" (AppN (AppN (VarN "x1") (AbsN "x3" (AppN (AppN (VarN "x3") (VarN "x1")) (VarN "x2")))) (VarN "x2")))


text:
Q: Inject UTM Parameter into Contact form using jQuery I am trying to inject a UTM parameter into our contact form. The contact form we are using is powered by FreshSales CRM and allows user to add hidden fields which should allow this to work.
The Parameters I want to pass are "Source, Medium and Campaign" and the UTM would look as follows:
?utm_source=google&utm_medium=cpc&utm_campaign=Conversion
I found the below code in a resource, does this need to be defined for each parameter or will this pull the entire UTM?
beforeSubmit: function()
{
console.log("Before submit hook triggered.");
WebForm.$('<input>').attr({
           type: 'hidden',
           name: 'lead[custom_field][cf_utm_param]',
           value: getQueryVariable('utm_param')
         }).appendTo('.fs-webform-container form');
}

Any help would be very much appreciated. Thanks!

A: So I got this working to pass UTM values into the contact form. We had to create a Tag in Google Tag Manager to store the UTM value in a Cookie so if the user looks at multiple pages we can store this information.
Code below if anyone needs it:
 <script>
var WebFormEvent = {
  afterInstall: function(){
    console.log("After installation hook triggered. updated");
  },
  beforeSubmit: function(){
  function getCookie(cname) {
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for(var i = 0; i <ca.length; i++) {
      var c = ca[i];
      while (c.charAt(0) == ' ') {
        c = c.substring(1);
      }
      if (c.indexOf(name) == 0) {
        return c.substring(name.length, c.length);
      }
    }
    return "";
  }

  const gtmCompaignUrl = new URL(getCookie('__gtm_campaign_url'));

  function getQueryVariable(variable) {
    var query = gtmCompaignUrl.search.substring(1) || "";
    var vars = query.split('&');
    for (var i = 0; i < vars.length; i++) {
      var pair = vars[i].split('=');
      if (decodeURIComponent(pair[0]) == variable) {
        return decodeURIComponent(pair[1]);
      }
    }
  }
  const values = {
    source: getQueryVariable('utm_source'),
    medium: getQueryVariable('utm_medium'),
    campaign: getQueryVariable('utm_campaign'),
  }

  console.log("Before submit hook triggered.", values);
  WebForm
    .$('<input>')
    .attr({
      type: 'hidden',
      name: 'lead[custom_field][cf_utm_source]',
      value: values.source,
    })
    .appendTo('.fs-webform-container form');

  WebForm
    .$('<input>')
    .attr({
      type: 'hidden',
      name: 'lead[custom_field][cf_utm_medium]',
      value: values.medium,
    })
    .appendTo('.fs-webform-container form');

  WebForm
    .$('<input>')
    .attr({
      type: 'hidden',
      name: 'lead[custom_field][cf_utm_campaign]',
      value: values.campaign,
    })
    .appendTo('.fs-webform-container form');
  }
}
</script>


text:
Q: Add Fade Transition to older Unslider script? Is there a simple way to add a fade transition to this script?  Based on the manner of it shuffling the items from left to right I didn't think it was possible.  May just use another script but figured it didn't hurt to get a second opinion.
(function(e, t) {
if (!e) return t;
var n = function() {
    this.el = t;
    this.items = t;
    this.sizes = [];
    this.max = [0, 0];
    this.current = 0;
    this.interval = t;
    this.opts = {
        speed: 500,
        delay: 3e3,
        complete: t,
        keys: !t,
        dots: t,
        fluid: t
    };
    var n = this;
    this.init = function(t, n) {
        this.el = t;
        this.ul = t.children("ul");
        this.max = [t.outerWidth(), t.outerHeight()];
        this.items = this.ul.children("li").each(this.calculate);
        this.opts = e.extend(this.opts, n);
        this.setup();
        return this
    };
    this.calculate = function(t) {
        var r = e(this),
            i = r.outerWidth(),
            s = r.outerHeight();
        n.sizes[t] = [i, s];
        if (i > n.max[0]) n.max[0] = i;
        if (s > n.max[1]) n.max[1] = s
    };
    this.setup = function() {
        this.el.css({
            overflow: "hidden",
            width: n.max[0],
            height: this.items.first().outerHeight()
        });
        this.ul.css({
            width: this.items.length * 100 + "%",
            position: "relative"
        });
        this.items.css("width", 100 / this.items.length + "%");
        if (this.opts.delay !== t) {
            this.start();
            this.el.hover(this.stop, this.start)
        }
        this.opts.keys && e(document).keydown(this.keys);
        this.opts.dots && this.dots();
        if (this.opts.fluid) {
            var r = function() {
                n.el.css("width", Math.min(Math.round(n.el.outerWidth() /
                    n.el.parent().outerWidth() *
                    100), 100) + "%")
            };
            r();
            e(window).resize(r)
        }
        if (this.opts.arrows) {
            this.el.parent().append(
                '
←→
'
            ).find(".arrows span").click(function() {
                e.isFunction(n[this.className]) && n[
                    this.className]()
            })
        }
        if (e.event.swipe) {
            this.el.on("swipeleft", n.prev).on("swiperight", n.next)
        }
    };
    this.move = function(t, r) {
        if (!this.items.eq(t).length) t = 0;
        if (t < 0) t = this.items.length - 1;
        var i = this.items.eq(t);
        var s = {
            height: i.outerHeight()
        };
        var o = r ? 5 : this.opts.speed;
        if (!this.ul.is(":animated")) {
            n.el.find(".dot:eq(" + t + ")").addClass("active").siblings()
                .removeClass("active");
            this.el.animate(s, o) && this.ul.animate(e.extend({
                left: "-" + t + "00%"
            }, s), o, function(i) {
                n.current = t;
                e.isFunction(n.opts.complete) && !r &&
                    n.opts.complete(n.el)
            })
        }
    };("sliderbg").fadeOut
    this.start = function() {
        n.interval = setInterval(function() {
            n.move(n.current + 1)
        }, n.opts.delay)
    };
    this.stop = function() {
        n.interval = clearInterval(n.interval);
        return n
    };
    this.keys = function(t) {
        var r = t.which;
        var i = {
            37: n.prev,
            39: n.next,
            27: n.stop
        };
        if (e.isFunction(i[r])) {
            i[r]()
        }
    };
    this.next = function() {
        return n.stop().move(n.current + 1)
    };
    this.prev = function() {
        return n.stop().move(n.current - 1)
    };
    this.dots = function() {
        var t = '
';
        e.each(this.items, function(e) {
            t += '<li class="dot' + (e < 1 ? " active" :
                "") + '">' + (e + 1) + "
"
        });
        t += "
";
        this.el.addClass("has-dots").append(t).find(".dot").click(
            function() {
                n.move(e(this).index())
            })
    }
};
e.fn.unslider = function(t) {
    var r = this.length;
    return this.each(function(i) {
        var s = e(this);
        var u = (new n).init(s, t);
        s.data("unslider" + (r > 1 ? "-" + (i + 1) : ""), u)
    })
}})(window.jQuery, false)

A: Look this fork, add the fade opt: https://github.com/jeremymlane/unslider


text:
Q: Changing Button Text Color I just need a simple button in clear color with black text inside. But the base button have white text. I need something to change the text color. My curent app
<View style={styles.fastlog}>
  <Button style={styles.bouton}
    title= "Connexion avec Facebook"
    color= "#A2FFA1"/>
  <Button style={styles.bouton}
     title= "Connexion avec Google"
     color= "#A2FFA1"/>
</View>

this works, i have the green button, but i cant find for the text

A: Use Text inside Button and give color to text.
<Button
   style={styles.bouton}
   color= "#A2FFA1"
>
 <Text style={{color: '#fff'}}>Connexion avec Facebook</Text>
</Button

Reference: https://github.com/GeekyAnts/NativeBase/issues/477

A: For this kind of situation i would suggest that you to use a third-party library or create a customButtonComponent as the Button component accessible from react-native do not have a lot of styling chances.
Note also that the prop color you are using changes the background color of the button only in Android, while it changes the text color in iOS.
Using a set of TouchableOpacify and Text you should be able to create a custom Button component stylable trough your own props and styles

A: Button in react native has limited Styling property
You can use TouchableOpacity or TouchableHeighlight with Text Property Inside it,
So at the end you can use Styling property of View as Touchable Component as well as Text Property as well
    <TouchableOpacity style={{...yourStytles}} >
        <Text style={{...yourTextStyles}}></Text>
    </TouchableOpacity>

A: On Android
const styles = StyleSheet.create({
  buttonSearch: {
    backgroundColor: "#F1F1F1",
    borderColor: "#D5D5D5",
    borderWidth: 1,
    borderLeftWidth: 0,
    borderRightWidth: 0,
    borderTopWidth: 0,
    borderRadius: 0,
  },
  buttonTitleSearch: {
    color: "#33353D",
  },
});

<Button
  navigation={this.props.navigation}
  title={
    this.state.searchPackageId
      ? "Package Id: " + this.state.searchPackageId
      : "Package Id: All"
  }
  // type="outline"
  buttonStyle={styles.buttonSearch}
  titleStyle={styles.buttonTitleSearch}
  onPress={() => {
    var navigation = this.props.navigation;
    console.log(this.state);
    navigation.navigate("PackageIdInput", {
      packageId: this.state.searchPackageId,
      updatePackageId: updatePackageId,
    });
  }}
/>

We can go to the index.d.ts to see the format of the component.

A: <Button
   style={styles.bouton}
   color= "#A2FFA1"
   title="this is the title of your button"

>
 <Text style={{color: '#fff'}}>Connexion avec Facebook</Text>
</Button>

You need to explicitly add title! This is if you have not solved it yet ,


text:
Q: How to ignore specific lines from being redirected I have a program that I could run by feeding it some instructions from an input file by redirection. My input file looks like this:
alpha
5
2
run
7
quit

Now, I run it like this:
myprogram < input_file

However, sometimes I need to add some comments to the input file to make it clear, e.g
# The name of value
alpha
# The acceleration
5
# The distance
2
run
7
quit

Unfortunately, now I can't redirect it to the program because It will not ignore the lines starting with #
How can I ignore those comment lines before redirecting it to myprgram?

A: You can use grep to filter out lines beginning with "#":
grep -v '^#' input_file | myprogram

The string passed to grep is a regular expression. It matches the beginning of the line (^) followed by #. -v inverts the logic so it shows lines NOT matching this pattern.
Generally I would choose grep to simply show/discard whole lines and sed if I wanted to modify data within lines. But of course the sed solution works as well.

A: Use sed to filter out lines with comments before giving it to your program. You could choose one of those forms (but the second, process substitution, is not supported by all shells):
sed '/^#/d' input_file | myprogram
myprogram < <(sed '/^#/d' input_file)

/^#/ is the regex that matches any line that begins with #, d is the command to delete those lines from the output. (Do not worry, input_file won't be modified by sed).


text:
Q: Laravel Horizon Dashboard Explanation
Hi All, I know its a very basic and generic question but had no choice but to ask, The highlighted options, what are these and how do they appear and what do they represent. This is a general image taken from a web article.

A: I've never fiddled much with horizon personally, so please bear with me. It would appear that the colorful-mountain-ree5ob2u-worker-1-Ro2v and colorful-mountain-ree5ob2u-worker-2-uz4R are representative of the machine/environment name(s) on which horizon is running.
This is an example I took from the Laravel/Horizon GitHub page:

And this is an example screenshot from my local Homestead environment:

They appear on the Horizon page on your Laravel application yoururlhere.test/horizon by running the following command php artisan horizon.
The workers themselves are found in the horizon.php configuration file and are set up like this:
    'local' => [
        'supervisor-1' => [
            'connection' => 'redis',
            'queue' => ['default'],
            'balance' => 'simple',
            'processes' => 3,
            'tries' => 1,
        ],
    ],

The name also appears to be appended by a seemingly random 4-character text string, which changes every time the php artisan horizon command is ran.


text:
Q: Convergence of a series of vectors in a Banach space Let $\sum_{k=1}^\infty\lambda^{k-1}\boldsymbol{v}_k$ be a series of vectors where $\lambda^{k-1}\in\mathbb{C}$, or $\lambda^{k-1}\in\mathbb{R}$, and the $\boldsymbol{v}_k$ belong to a Banach space.
I think I have been able -please correct me if I am wrong- to prove that if $\sum_{k=1}^\infty|\lambda^{k-1}|\|\boldsymbol{v}_k\|$ converges, then $\sum_{k=1}^\infty\lambda^{k-1}\boldsymbol{v}_k$ does.
Can we define a convergence radius  as we do when $\boldsymbol{v}_k\in\mathbb{C}$, outside of which $\sum_{k=1}^\infty\lambda^{k-1}\boldsymbol{v}_k$ does not exist? If we can, how can it be proved? Thank you so much for any answer!

A: The statement you say you have been able to prove is correct. In fact, it's very close to a characterization of Banach spaces. A normed linear space $X$ is Banach if and only if every absolutely summable series in convergent, i.e. if every series $\sum_{n=1}^\infty a_n$, $a_n\in X$ with
$$
\sum_{n=1}^\infty \Vert a_n \Vert_X < \infty
$$
converges in $X$.
This isn't exactly your case since you are talking about power series. This is essentially the idea of Banach-space valued analytic functions: see http://planetmath.org/banachspacevaluedanalyticfunctions for definitions and some properties, and Where does the theory of Banach space-valued holomorphic functions differ from the classical treatment? for an interesting question outlining some more features of the theory. They are quite surprisingly similar to analytic functions of a complex variable.
In principle, of course you can define a radius convergence for a Banach-space valued power series: the largest radius $R$ for which the power series converges for all $|\lambda| < R$. A priori, we won't know for a given power series if this $R$ is positive - just like for the usual real and complex power series. We also won't know in general about convergence outside the disc of convergence, which is also the same for real and complex power series. (You can't say anything about convergence at the boundary of the disc of convergence without having a specific power series in mind.)


text:
Q: Continuously Measure 3-Phase Motor Current What methods are there for continuously monitoring the current in a 3-phase servo motor for a CNC machine and giving an alarm when the current is less than some value?

A: You need a current transformer (or three).

If you connect a resistor to the transformer's secondary winding a current through the sensed wire will cause a voltage across the resistor. The voltage is proportional to the current so will be a sine wave.
If you'd rather like a DC output proportional to the current you can use an i-Snail-V current transformer. It's self-powered and the i-Snail-V10 version for instance gives you 5 V out for 10 A. Other versions with other sensitivities exist.

A: A variety of current sense techniques exist.
Hall effect sensors are nice for measuring large currents through a wire at high voltages. Some have analog out, eating up one of the analog inputs on your microcontroller. Others have an integrated internal ADC, with digital pins that directly connect to your microcontroller. A few also have an integrated power FET driver, and are smart enough to unconditionally turn off the FET when it measures over-current.
Perhaps you could somehow use that output to drive an alarm instead of a FET.
The Allegro Hall effect sensor chips look nice.
Related: How can I sense the motor's current?


text:
Q: Difference between "acting for" and "standing for" What is the difference between "acting for" and "standing for"?
See this text for example (H. Pitkin, The Concept of Representation):

A: I think the primary difference is in context. When you act for something, you don't necessarily have to support it or believe in it. It could be required of you, a favor for someone, or something related to unexpected cirrcumstances. In contrast, when you stand for something, it typically relates to your conviction surrounding the thing in question. I would suggest tying "standing for" to opinions, beliefs, and morality.
Edit: Ahh. I posted prior to the addition of the clarifying picture. In that case, I'm not really sure.

A: That really clears up what you're asking.
Here, 'act for' = 'act on behalf of' and requires an agent, a sentient actor who/that chooses to act (on X's behalf).
'Stand for' means 'represent', which may equate to 'act for', but may be used as impassively as in 'x stands for the length (in metres) of the swimming pool'.

A: My professor explained it like this: standing for means you are representing a group you are part of. Acting for is virtual representation. It means you take no part in the group you represent. In both cases the represented group choses the person who is to represent them (you cannot represent someone if they do not agree with it).


text:
Q: How to get R and S values from ECDSA signature using PHP I am working on Signature of data using ECDSA from Starkbank library and I can get the base64 format of the signature value MEUCIALlD6Xsd0Xdj7XTrD2gP4Q3PlssTxLOCUi6R8FbXMlbAiEAmW8HLiBnhaBBPzIL64FGzFYzUwF1HfX+a8ep5/NpI0k= and the Der value is 0E ���wEݏ�Ӭ=�?�7>[,O� H�G�[\�[!�o. g��A?2�F�V3Su��kǩ��i#I
but I want to know the R and S values with the length as well, how can I achieve it?
my PHP code is:
<?php
require_once "src/ellipticcurve.php";
#privateKey from PEM string
$privateKey = EllipticCurve\PrivateKey::fromPem("
    -----BEGIN EC PRIVATE KEY-----
    MIGEAgEAMBAGByqGSM49AgEGBSuBBAAKBG0wawIBAQQgPUAdAJuELXoxEumrKUPd
    yHLP9bITTV+yOSw5q1H8W/2hRANCAASW6MSUA/wJRcj0AljN0tnpMBp5ISqTp8j/
    rY7C2BXCXyy03V/lP7jn0LSgJvykVyNRPXfA4zjpFRaOUNWUBNuU
    -----END EC PRIVATE KEY-----
");
$message = "j4+wDOaRLRQn7oweoCbob1WDaqPRCTHzonn08b+dJr0";
$signature = EllipticCurve\Ecdsa::sign($message, $privateKey);

# Generate Signature in base64. This result can be sent to Stark Bank in header as Digital-Signature parameter

$base64 = $signature->toBase64();
$der = $signature->toDer();
echo "\n" . $der;
echo "\n" . $base64;

$publicKeyPem = EllipticCurve\Utils\File::read("publicKey.pem");

$publicKey = EllipticCurve\PublicKey::fromPem($publicKeyPem);

# To double check if message matches the signature
//$publicKey = $privateKey->publicKey();
echo "\n" . EllipticCurve\Ecdsa::verify($message, $signature, $publicKey);
?>

the ECDSA config which I am working on:
digest_alg = "sha256",
private_key_bits = 2048,
private_key_type = OPENSSL_KEYTYPE_EC,
curve_name = secp256k1,

A: You Can Use SOP/ASN1 To get the Sequence from DER.
Try https://lapo.it/asn1js to find the Positions from R and S. Use bin2hex($signature->toDer()) to get Hex-Encoded ASN.1
It depends on the Type of your $signature->toDer().
Maybe your Hexstring is already Sequence, then following two ANS.1-Integers (R/S).
Then use for e.g.
$seq = \Sop\ASN1\Type\UnspecifiedType::fromDER($signature->toDer())->asSequence();
$seq->at(0)->asInteger()...
$seq->at(1)->asInteger()...


text:
Q: Can I continue the for loop from callback inside the loop? I am using selenium concurrently element checking using timer in c#. If element found the call back will call then I need to continue the for loop.
This is my code, it is not working. Any Suggestions?
for (i = 0; i < list.length(); i++) {
    //statement
    mycallback((s) => { if(s) continue; }); // continue here
    //statement
}

A: in C# you can use labels to go where you want.
they transfer the program control directly to a labeled statement
look at the snippet below:
for (i = 0; i < list.length(); i++) {
    //statement

    mycallback((s) => { if(s) goto myLabel; });

    // continue here
    myLabel: // parts of your code

    //statement
}

it is not recommended though that could be useful in some cases.
more info about this syntax:
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/goto
more discussion about using labels: Does anyone still use [goto] in C# and if so why?


text:
Q: Recreation math : Fill the box type problem with equal sum of row and column
Today I solve an interesting recreational math problem which took some time.
First I will briefly explain the situation of the problem.  Look above figure.

(1) a,b,c,d,e,f,g,h,i,j are one of 1,2,3,4,5,6,7,8,9,10

(2) the sum of each row and columns are the same. (i.e., a+b+c+d = a+e+g, ...)

Find a,b,c,d,...

I tried to solve this by making equations but for me, that direction was too complicated.
Instead, I noticed that e and f should be big, and putting $x$ be the sum of each row or column
and make 4x = 55 + a + b + c + d, hence $x=\frac{55}{4} + \frac{a+b+c+d}{4}$, and from the assumption I have $14\leq x \leq 22$. letting $e=10, f=9$ and solve $x = a+10+g = d+ 9 + j$ with many trials and errors I obtain $x=18$ and $a=2, g=6, d=8, j=1, b=5, c=3, h=4, i=7$.
Is there any simple way to solve this problem? Please let me know the simple strategy.

A: Some restrictions could be derived:
if $$x = a+b+c+d = g+h+i+j,$$
then
$$
2x+e+f = 55,
$$
so
$$
18\le x \le 26.
$$
But:
 $x=26$ doesn't work, since then $e+f=3$, so $e=1$ (if $e<f$), and $a+g=25$.
 $x=25$ doesn't work, since then $e+f=5$, so $e\le 2$ (if $e<f$), and $a+g\ge 23$.
 $x=24$ doesn't work, since then $e+f=7$, so $e\le 3$ (if $e<f$), and $a+g\ge 21$.
 $x=23$ doesn't work, since then $e+f=9$, so $e\le 4$ (if $e<f$), and $a+g\ge
19$, which is possible for $e=4$, but isn't possible for corresponding $f=5$ and $d+j=18$.

Actually there are ten solutions (with sums $18$, $19$, $20$, $22$) (with $a<g$, $e<f$, $b<c$, $h<i$).

Therefore there is no unique short algorithm to determine "proper" solution.

There should be some "trial-and-error" part here, I guess.
Just few examples :
 x=18:
 1 4 7 6
 9     10
 8 3 5 2

 x=18:
 4 1 7 6
 9     10
 5 3 8 2

 x=19:
 1 5 6 7
 8     9
10 2 4 3

 x=20:
 4 1 5 10
 7     8
 9 3 6 2

 x=22:
 8 2 3 9
 4     7
10 1 5 6


text:
Q: Invariant operators in the Heisenberg picture? Background + My attempt
I was recently thinking about the Heisenberg picture in Special Relativity:
$$ \frac{dO(t)}{dt}=\frac{dU^\dagger \hat OU}{dt} = U^\dagger\frac{[H,O]}{-i \hbar}U $$
However this is not an invariant quantity. So I thought I could define a new invariant operator:
$$ \frac{d U^\dagger \hat OU}{d t}. \frac{dt}{d\tau} = \gamma \frac{[H,O]}{-i \hbar} $$
where $\gamma(v(t))=\frac{1}{\sqrt{1-(v/c)^2}} $
Questions
Is this correct? I couldn't find this on the internet ... Also how does one define an invariant operator in special relativity and for any arbitrary metric?


text:
Q: PowerPivot: how to calculate a weighted average in a pivot table? I am new to PowerPivot within Excel, but am familiar with SQL.
I import a table from my SQL server into PowerPivot, containing the results of some surveys; the columns are: City, State, Population, avg income, avg income x population.
I need to create a Pivot Table showing the weighted average income by State.
If the source of the data were an Excel sheet, I'd add a calculated field to the pivot table, calculating [avg income x population] / [Population].
I cannot seem to that in my case, since the source is a PowerPivot data source.
Suggestions?
I understand I can add calculated fields and measures to the PowerPivot table, but that's not really what I am after.
I am sure it's because my google skills are subpar, but I have also spent lots of time searching for solutions, to no avail.
E.g. these discussions show how to add a field to the powerpivot source, but it's not clear to me how you add a calculated field to a Pivot table which reads from PowerPivot.
PowerPivot formula for row wise weighted average
DAX - 2 phased weighted average with 2 different weight measures


text:
Q: Using "Neither am I" to introduce an additional comment I was wondering whether I can use "neither am I" to add an other comment to a statement. For example,

I am not ignorant to the shortcomings ..., neither am I blind to the
  negative consequences ....

In my opinion, it is somehow different to
Neither am I / me neither in a specific context
but I could be wrong. Can at least someone tell me whether it sounds weird?


text:
Q: How to configure Glassfish 3.1.2.2 that I can use admin service remote with security enabled and local with security disabled I need a way to use Glassfish 3.1.2.2 admin service (REST call to deploy and configre) from a remote machine and from local machine (command line and applications).
It is clear that for remote access it is necessary to enable secure admin. If we enable secure admin it will break all local access from applications. These application can not be changed to using https to access the admin service. Only thing I can change is that we can use a different port.
I see two possible ways for me:

*

*Using a hack.  So I can administrate with secure administrate disable. So I can use plan http. For use a possible solution, because this machine used internally in a test environment.

*Configure Glassfish that we can use admin service remote via secure access https and from a local environment with http.

We prefer solution 1, because it fit better in our environment and we have lesser effort. At the moment I see no way or exist a solution (not for production)?
I tried something for solution 2, simular to http-listener-1 http-listener-2. So use two ports 4848 for local unsecure access and as example 4949 for remote secure access.But I always fail with configuration. So I start with a step by step configuration. First enable admin interface oon two ports and as second step I want to add the secure access to the new port admin-listener. But I got only one of the ports working.Please can anyone help me with target configuration? Any domain.xml will be welcome.
Thanks florian

A: You can try to use SSH and run asadmin utilities from remote machine.


text:
Q: form-validation in codeigniter <?php echo validation_errors(); ?>
<?php echo form_open('verifylogin'); ?>
  Username:
  <input type="text" size="20" id="username" name="username"/>

  Password:
  <input type="password" size="20" id="password" name="password"/>

  <input type="submit" value="Login"/>
</form>

I use that code to validate a filled in form but the browser shows nothing after I submit. The URL of my browser is stuck at http://example.com/index.php/verifylogin
verifylogin.php is defined like this
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class VerifyLogin extends CI_Controller {

 function __construct()
 {
   parent::__construct();
   $this->load->model('user','',TRUE);
 }

 function index()
 {
   //This method will have the credentials validation
   $this->load->library('form_validation');

   $this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
   $this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_check_database');

   if($this->form_validation->run() == FALSE)
   {
     //Field validation failed.  User redirected to login page
     $this->load->view('login_view');
   }
   else
   {
     //Go to private area
     redirect('home', 'refresh');
   }

 }

 function check_database($password)
 {
   //Field validation succeeded.  Validate against database
   $username = $this->input->post('username');

   //query the database
   $result = $this->user->login($username, $password);

   if($result)
   {
     $sess_array = array();
     foreach($result as $row)
     {
       $sess_array = array(
         'id' => $row->id,
         'username' => $row->username
       );
       $this->session->set_userdata('logged_in', $sess_array);
     }
     return TRUE;
   }
   else
   {
     $this->form_validation->set_message('check_database', 'Invalid username or password');
     return false;
   }
 }
}
?>

A: class Auth extends CI_Controller{

    public function __construct(){parent::__construct();}
     /**
     * Login Form
     *
     * $route['login'] = 'auth/login_form';
     *
     */
    public function login_form(){
         $this->load->view('login_form');
    }
    /**
     * Login Validation
     *
     * $route['login/check'] = 'auth/login_check';
     * Point your form to login/check
     */
    public function login_check()
    {
        if($this->form_validation->run() == TRUE)
        {
            //form validates...
        }else
        {
             //no redirect! just show for again!
             $this->login_form();
        }
    }
}


text:
Q: How to stop showing sticky floating footer bar on specific page and posts in wordpress? I  have added a sticky floating footer bar to my site and it works great but I want to hide or stop showing the footer bar on specific posts and pages on my site. Check live demo https://whatsapgroupslink.com/
I used some CSS and js code to implement this footer bar.
First I used this code in elements and hook to generate after footer and display rule is the entire site.

    Get Free Access and VIP Support<button id="wplogout-closebar" type="button">X</button>

Second I use this code in elements and hook to wp footer and display rule is the entire site.


text:
Q: What's os.geteuid() do? I was trying to debug a Python 2 script running on Raspbian (Raspberry Pi flavoured Debian Linux) which had code like
euid = os.geteuid()
if euid != 0:
    print("you must be root!")
    exit(1)

It seemed like, in the user's environment, euid would sometimes be nonzero even if the script was called with sudo.
To investigate whether this was actually the case, I tried to figure out what os.geteuid() is actually doing.
Since the os module is pretty OS-specific by its nature, the source doesn't actually have a clear definition for os.geteuid().
I also tried hg cloneing the source and compiling it, then using inspect.findsource(os.geteuid), but:
TypeError: <built-in function geteuid> is not a module, class, method, function, traceback, frame, or code object

It's... a builtin? Then "geteuid" in dir(__import__("__builtin__")) should be True, but it isn't.
Is geteuid's definition hidden because it could be spoofed into returning the wrong thing (and that would be bad)? Where can I see these sorts of functions' actual source?

A: ASCII stupid question, get a stupid ANSI.

I did try full-text searching the source, but apparently I used the wrong command the first time and gave up.
$ grep -rnw '.' -e "geteuid"
./Misc/setuid-prog.c:129:    uid_t euid = geteuid();
./Lib/site.py:209:    if hasattr(os, "getuid") and hasattr(os, "geteuid"):
./Lib/site.py:211:        if os.geteuid() != os.getuid():
./Lib/test/test_shutil.py:84:    @unittest.skipIf(hasattr(os, 'geteuid') and os.geteuid() == 0,
./Lib/test/test_httpservers.py:339:            if os.name == 'posix' and os.geteuid() != 0:
./Lib/test/test_httpservers.py:395:@unittest.skipIf(hasattr(os, 'geteuid') and os.geteuid() == 0,
./Lib/test/test_spwd.py:8:@unittest.skipUnless(hasattr(os, 'geteuid') and os.geteuid() == 0,
./Lib/test/test_posix.py:44:                             "getegid", "geteuid", "getgid", "getgroups",
./Lib/test/test_argparse.py:1532:@unittest.skipIf(hasattr(os, 'geteuid') and os.geteuid() == 0,
Binary file ./Lib/tarfile.py matches
./Lib/rexec.py:148:                      'getcwd', 'getuid', 'getgid', 'geteuid', 'getegid')
Binary file ./Modules/posixmodule.o matches
./Modules/posixmodule.c:4047:"geteuid() -> euid\n\n\
./Modules/posixmodule.c:4053:    return _PyInt_FromUid(geteuid());
./Modules/posixmodule.c:8944:    {"geteuid",         posix_geteuid, METH_NOARGS, posix_geteuid__doc__},
./Doc/library/rexec.rst:234:   'times', 'uname', 'getpid', 'getppid', 'getcwd', 'getuid', 'getgid', 'geteuid',
./Doc/library/os.rst:136:.. function:: geteuid()
Binary file ./python matches
Binary file ./libpython2.7.a matches

./Modules/posixmodule.c:4053, indeed:
#ifdef HAVE_GETEUID
PyDoc_STRVAR(posix_geteuid__doc__,
"geteuid() -> euid\n\n\
Return the current process's effective user id.");

static PyObject *
posix_geteuid(PyObject *self, PyObject *noargs)
{
    return _PyInt_FromUid(geteuid());
}
#endif

I don't know what I expected, subprocess.check_output(["id"])?
It uses the C standard library, it's never wrong.


text:
Q: Cannot get frame or center for elements inside UIView that is inside UITableView I have an UITableView where first comes Table View Section following by UIView (bound to IBOutlet _myView) with some controls inside (e.g. UITextField, bound to IBOutlet _durationField). All this is done in the Storyboard. I want to move that _durationField dynamically, so I need to modify center or frame properties. However, this code inside viewDidLoad returns zero values:
CGRect durationRect = _durationField.frame;

whereas labels inside TableCell and _myView frame properties return real values, e.g. this doesn't return zeros:
CGRect viewRect = _myView.frame;

Also changing the frame property of _durationField doesn't reflect in the UI. Actually I get zero values for all controls inside _myView although they are properly bound to IBOutlet's in the code. Moreover, I can set _durationField.text in viewDidLoad and it works fine.
Any ideas? It looks like I'm missing something simple.
The first suggested solution with viewWillLayoutSubviews allows moving the element indeed but only after the view is rendered. So the user sees how it's moving. This is not a desirable behavior. I'd like to move the element dynamically before the view is rendered.

A: In viewDidLoad, the UI is not laid out yet, you should move the code that adjusts the frame to viewWillLayoutSubviews (make sure you call the super class implementation first)


text:
Q: Issue when loading data from cloud storage, at least an error message improvement is needed When I try to load multiple files from cloud storage larger jobs almost always fail. When I try to load an individual file that works, but loading batches is really much more convenient.
Snippet:
Recent Jobs
Load 11:24am
gs://albertbigquery.appspot.com/uep/201409/01/wpc_5012_20140901_0002.log.gz toalbertbigquery:uep.201409
Load 11:23am
gs://albertbigquery.appspot.com/uep/201409/01/wpc_5012_20140901_0001.log.gz toalbertbigquery:uep.201409
Load 11:22am
gs://albertbigquery.appspot.com/uep/201409/01/* toalbertbigquery:uep.201409
Errors:
File: 40 / Line:1 / Field:1, Bad character (ASCII 0) encountered: field starts with: <�>
File: 40 / Line:2 / Field:1, Bad character (ASCII 0) encountered: field starts with: <5C���>}�>
File: 40 / Line:3 / Field:1, Bad character (ASCII 0) encountered: field starts with: <����W�o�>
File: 40 / Line:4, Too few columns: expected 7 column(s) but got 2 column(s). For additional help:
File: 40 / Line:5, Too few columns: expected 7 column(s) but got 1 column(s). For additional help:
File: 40 / Line:6, Too few columns: expected 7 column(s) but got 1 column(s). For additional help:
File: 40 / Line:7, Too few columns: expected 7 column(s) but got 1 column(s). For additional help:
File: 40 / Line:8 / Field:1, Bad character (ASCII 0) encountered: field starts with: <��hy�>
The worst with this problem is that I don't know which file is "File: 40" the order seems random, otherwise I could remove that file and load the data, or try to find the error in the file.
I also strongly doubt that there even is an actual file error, for example in the above case when I removed all files but _0001 and _0002 (that worked fine to load as single files) I still get this output:
Recent Jobs
Load 11:44am
gs://albertbigquery.appspot.com/uep/201409/01/* toalbertbigquery:uep.201409
Errors:
File: 1 / Line:1 / Field:1, Bad character (ASCII 0) encountered: field starts with: <�>
File: 1 / Line:2 / Field:3, Bad character (ASCII 0) encountered: field starts with:
File: 1 / Line:3, Too few columns: expected 7 column(s) but got 1 column(s). For additional help:
File: 1 / Line:4 / Field:3, Bad character (ASCII 0) encountered: field starts with:
Sometimes though the files load just fine, otherwise I'd expect that multiple file loading was all wrecked.
Info:
Average file size is around 20MB, usually a directory is 70 files somewhere between 1 and 2 GB.

A: It looks like you're hitting a BigQuery bug.
When BigQuery gets a load job request with a wildcard pattern (i.e. gs://foo/bar*) we first expand the pattern to the list of files. Then we read the first one to determine the compression type.
One oddity with GCS is that there isn't a real concept of a directory. That is gs://foo/bar/baz.csv is really bucket: 'foo', object: 'bar/baz.csv'. It looks like you have empty files as placeholders for your directories (as in gs://albertbigquery.appspot.com/uep/201409/01/).
This empty file doesn't play nicely with the bigquery probe-for-compression type, since when we expand the file pattern, the directory dummy file is the first thing that gets returned. We then open the dummy file, and it doesn't appear to be a gzip file, so we assume the compression type of the entire load is uncompressed.
We've filed a bug and have a fix under testing. Hopefully the fix will be out next week. In the mean time, your options are to either expand the pattern yourself, to use a longer pattern that won't match the directory (as in  gs://albertbigquery.appspot.com/uep/201409/01/wpc*), or to delete the dummy directory file.


text:
Q: Can "same" be postpositive? Can we put the sentence "same as" after a noun? For example,

*

*He drives the same car as you.

*He drives the car same as you.

Can we use the latter expression instead of the former?
I seldom see the usage like the latter, but some of my colleagues use it.

A: I don't think either sentence is good English. These would be better:

*

*He drives the same car as you

*The car he drives is the same as yours

The "same as yours" needs to modify "car" instead of "drives."


text:
Q: How to scroll up one line in terminal? When I enter several lines command and the cursor is at the end of the last line. But I if I want to edit the last line command, how can I do it. For now I can only type ← several times till I reach the beginning of the line and then move to the line above.
The command is like this:
➜  src git:(master) ./configure --with-features=huge \
>                   --enable-rubyinterp \
>                   --enable-pythoninterp \
>                   --enable-perlinterp \
>                   --enable-cscope

A: If you're using Bash or zsh, and you want to move the cursor inside the line itself, try ShiftCtrl↑ & ShiftCtrl↓, and if you want to jump between commands, just try ↑ ↓.
More shortcuts:
Ctrl + A or Home take you to the beginning of the line.
Ctrl + E or End take you to the end of the line.
Alt + B take you left (back) one word.
Alt + F take you right (forward) one word.
More information here:
The Keyboard Shortcuts for Bash

A: In Bash, you can open up the command in a text editor with CTRL-XCTRL-E so long as your $EDITOR environment variable is set. To set it you can export EDITOR=vim or put that in your .bashrc.
zsh do the same thing, but a keybinding needs to be configured.


text:
Q: RuntimeError: There is no current event loop in thread 'Thread-1'. asyncio, discord.py This code is for a discord bot that sends a message via a non-async function and I get the error. I understand from the error that there is no event loop, so maybe the solution is to create one. I don't know. Or maybe get_event_loop() is not necessary.
Exception in thread Thread-1:
Traceback (most recent call last):
  File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python38\lib\threading.py", line 932, in _bootstrap_inner
    self.run()
  File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python38\lib\threading.py", line 870, in run
    self._target(*self._args, **self._kwargs)
  File "c:/Users/LENOVO/Documents/Ada-online/Discord bot/main copy.py", line 19, in check_time
    asyncio.get_event_loop().create_task(channel.send("example message"))
  File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python38\lib\asyncio\events.py", line 639, in get_event_loop
    raise RuntimeError('There is no current event loop in thread %r.'
RuntimeError: There is no current event loop in thread 'Thread-1'

I am not familiar with discord.py yet so I would need some help. Here's my code:
import discord
import threading
import datetime
import time
import asyncio

intents = discord.Intents.default()
intents.message_content = True

client = discord.Client(intents=intents)

my_secret = 'bot_key'

def check_time():
    time.sleep(10)
    channel = client.get_channel(1027207022132863036)
    print('Channel:', channel)
    asyncio.get_event_loop().create_task(channel.send("example message"))
    while True:
        ndt = datetime.datetime.now()
        if ndt.strftime('%A') == 'Friday' and ndt.hour == 16 and ndt.minute == 29 and ndt.second == 5:
            asyncio.get_event_loop().create_task(channel.send("example message"))
        time.sleep(0.9)

@client.event
async def on_ready():
    print('We have logged in as {0.user}'.format(client))

@client.event
async def on_message(msg):
    print(msg.channel)
    msg_words1 = msg.content.split(' ')
    msg_words = []
    for i in msg_words1:
        msg_words.append(i.lower())

    if msg.author == client.user:
        return

    if ('zoom' in msg_words and 'when' in msg_words) or ('zoom' in msg_words and 'when?' in msg_words) or ('zoom?' in msg_words and 'when' in msg_words):
        await msg.channel.send('We have zoom every day from 16:00 to 17:30.')

t = threading.Thread(target=check_time)
t.start()

client.run(my_secret)

Thanks!

A: You are running the check_time function as a separate thread.  The asyncio event loop is thread-specific.  So if you want to do asyncio-stuff in a second thread, there must be a running event loop in that thread.
The function asyncio.get_event_loop(), if called from the main thread will create and set a new event loop.  This behavior has changed slightly in Python3.10 and will change some more in Python3.11.  But note what the docs say:
"If there is no current event loop set in the current OS thread, the OS thread is main, and set_event_loop() has not yet been called, asyncio will create a new event loop and set it as the current one."
But if the OS thread isn't main, a call to this function will raise an Exception, as you observe.  The fix is simple enough - create and set the event loop explicitly in your secondary thread:
def check_time():
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    # The rest of the code is unchanged
    time.sleep(10)
    channel = client.get_channel(1027207022132863036)
    print('Channel:', channel)
    asyncio.get_event_loop().create_task(channel.send("example message"))
    while True:
        ndt = datetime.datetime.now()
        if ndt.strftime('%A') == 'Friday' and ndt.hour == 16 and ndt.minute == 29 and ndt.second == 5:
            asyncio.get_event_loop().create_task(channel.send("example message"))
        time.sleep(0.9)

However, this is probably only one of your issues.  The event loop is an infinite loop, and your code also has one of those.  You can't have two such loops in the same task.  So you probably want to organize your program in a more task-like structure, for example:
async def tgif():
    channel = client.get_channel(1027207022132863036)
    print('Channel:', channel)
    asyncio.create_task(channel.send("example message"))
    while True:
        ndt = datetime.datetime.now()
        if ndt.strftime('%A') == 'Friday' and ndt.hour == 16 and ndt.minute == 29 and ndt.second == 5:
            asyncio.create_task(channel.send("example message"))
        await asyncio.sleep(0.9)

def check_time():
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    time.sleep(10)
    asyncio.run(tgif())

You need to look carefully at the documentation for time.sleep and asyncio.sleep, which are different in important ways.  I changed one of your time.sleep calls to asyncio.sleep because that seemed right; I don't understand why you have put those sleeps in your program, so I won't comment on that.
Also the new function that now contains your infinite loop, which I named tgif, needs to be declared with the async keyword, since it is a Task.
Unfortunately I don't know anything about discord, but at least this should get rid of the error.


text:
Q: Setting Android AutoCompleteTextView position relative to anchor view I've got an android AutoCompleteTextView (actually extended) and I'd like to control where the popup list of suggestions appears. For example above or below my anchor view.
Currently, the autocomplete seems to prefer below the anchor view unless the data it is trying to display needs more room (and that room is available above). Is there a way to set it to always appear in a certain orientation regardless of the size of data.
Thanks

A: i think you can use this:
myAutoCompleteTextView.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // TODO Auto-generated method stub
               myAutoCompleteTextView.dismissDropDown();
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                    int after) {
                // TODO Auto-generated method stub
                myAutoCompleteTextView.dismissDropDown();
            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub
                myAutoCompleteTextView.dismissDropDown();
            }
        });


text:
Q: Giving access to file from Tomcat to external user I have Tomcat setup with servlets. When the user request a file to download, then I send him the path to the file to download.
1-Currently the path is in C drive. Do you think I should move it to be somehwere under Tomcat?
2-How can I give the user access to the folder/file so he can download it?
3-Finally, if there are multiple files inside the folder. How can I ensure he can only see this file (i.e. if he manually changes the file name in the URL, he won't get the file with that modifed file name)
Thank you

A: One possibility:

*

*Yes move them over to tomcat say under   /myapp/resources/file_library

*when the users requests for a particular file ,  build a temp user directory and
copy the file in there and send the link to him , as in
/myapp/user_xyz/requestedfile#1

*Always maintain the temp location with only one file, i.e.  when the user requests another
file, clear the temp user-specific area and put the next file in .
/myapp/user_xyz/requestedfile#2


text: Q: mongodb upgrade from version 1.8 to 2.4 Hi I need to upgrade mongodb standalone server from 1.4.5 to 2.4 and a replica set from 1.8.3 to 2.4. I have got docs to upgrade from 2.2 to 2.4. But I am not able to get docs upgrading mongodb from version 1.4 to 2.4 or from 1.8 t o2.4. In one of the documents I found that to upgrade from 2.0 to 2.4, its first needed to upgrade to 2.2 and then to 2.4. So do I need to do gradual upgrade?


text:
Q: How can I send custom dimensions with the product impressions event in Google Analytics? I am currently trying to send custom dimension values with the product impressions event. Everything else seems to work but I am not able to report on the custom dimension values.
I have set up dimension8 and dimension 9 for star rating and review count. I have passed through these values to the object and it is successfully being sent.
dataLayer.push({
    'event': 'productDetailImpressions',
    'ecommerce': {
        'detail': {
            'actionField': {
                'list': 'PDP'
            },
            'products': [{
                'name': name,
                'id': id,
                'price': price,
                'brand': brand,
                'category': category,
                'variant': variant,
                'dimension8': reviewCount,
                'dimension9': starRating
            }]
        }
    }
});

I have set these custom dimensions up with product scope in GA.
I can view the tag and the information it is sending with a plugin in the browser, the values look correct.
However I am still not able to report on these values inside Google Analytics.
Is there anything I am doing wrong?
Thank you.

A: The scoping of dimensions required 2 things:
Configure scope in Google Analytics admin interface
See below screenshot:

Send custom dimension with the proper hit
Data is sent to Google Analytics with "hits". Hits are:

*

*page tracking hits

*event tracking hits

*ecommerce tracking hits social

*interaction hits

Now this doesn't mean that you should structure your dataLayer so that the custom dimensions are on the same level ase the object (eg user, product) you're trying to associate them with. Instead, you should follow the standard method for setting dimensions:
In Google Analytics, it is:
// Set the dimension
ga('set', 'cd1', 'Level 1');
// Send custom dimension along with a hit (eg pageview)
ga('send', 'pageview');

Now with Google Tag Manager, GTM doesn't send any hits to Google Analytics, it's just a tool for preparing your data and automating the use of GA. So an example on how to do it:
dataLayer.push({
    'event': 'productDetailImpressions',
    'dimension8': reviewCount,
    'dimension9': starRating,
    'ecommerce': {
        'detail': {
            'actionField': {
                'list': 'PDP'
            },
            'products': [{
                'name': name,
                'id': id,
                'price': price,
                'brand': brand,
                'category': category,
                'variant': variant,
            }]
        }
    }
});

Then create some dataLayer variables to read the custom dimension values:

Finally, assign those dimensions to your GA tags:

note: you could potentially make it work with the dataLayer you have, you would just have to replace your dataLayer variable to point to the right location, however I think it's bad practice because it leads to believe that dimensions have to be nested within the scoped object in order to work (which is not true) and it makes things harder to debug.


text:
Q: V-select issue in Vuetify 3 I'm using Vuetify 3.0.0-beta.0 ~ for my project (because it is the only version that supports vue3), and having a bit weird issue
I want to implement the same thing as described there https://codepen.io/reijnemans/pen/vYNadMo?editors=1010 with v-select involved, so I was needed to use Vuetify
copied snippet
          <v-select
            :items="items"
            label="Standard"
          >
            <template v-slot:selection="{ item, index }">
              {{ item.name }}</template>
            </template>
            <template v-slot:item="{ item }">
              {{ item.name }}</template>
          </v-select>

My Component:

<template>

            <v-col cols="10" lg="4" class="mx-auto">

Some Test H2

                <v-col class="d-flex" cols="12" sm="6">
                    <v-select
                        :items="items"
                        label="Standard">
                        <template v-slot:selection="{ item }">
                        {{ item.name }}
                        </template>

                        <template v-slot:item="{ item }">
                        {{ item.name }}
                        </template>

                    </v-select>
                </v-col>
          </v-col>

</template>

     <v-col cols="10" lg="4" class="mx-auto">

Some Test H2

        <v-col class="d-flex" cols="12" sm="6">
           <v-select
            v-model="value"
            :items="items"
            item-title="name"
            item-value="name"
            label="Standard">
              <template v-slot:item="{item}">
              <v-list-item
                :prepend-avatar="item.raw.image"
                :title="item.raw.name"
              />
            </template>
         </v-select>
        </v-col>
     </v-col>

A: In Vuetify 3, you need some workarounds to style the items in v-select, because the item slot resets the entire styling.
You should use the menu-props, with it you can pass props through to the v-menu component. It accepts an object with anything from /api/v-menu. This allows you to close the field on click.
In the item slot, you should use a v-list-item with an @click property to set the model.
I made an example here with a selection of symbols:

<template>
    <v-select
        v-model="form.symbol"
        :items="symbols"
        label="Symbol"
        :prepend-inner-icon="'mdi-'+form.symbol"
        :menu-props="{
            closeOnClick: true,
            closeOnContentClick: true,
        }"
    >
        <template v-slot:selection="{ item, index }">
            {{ item.value }}
        </template>

        <template v-slot:item="{ item, index }">
            <v-list-item
                :title="item.title"
                :prepend-icon="'mdi-'+item.title"
                @click="form.symbol = item.title"
            >
            </v-list-item>
        </template>
    </v-select>
</template>

I hope it helps you.