text:
Q: How to reset FIND function result before looping to another sheet? I would like to ask if you can help with the code below. On every sheet in my workbook there is the same kind of a table, however on each sheet the table has different location and values. I need to go through all sheets, search for table values on every sheet and then do some other operations with the values. I use Find function to determine header of the table and subsequently table range. The Find function does not work properly though as it keeps found address of "Header" cell from the first sheet for every other sheet. Is there any way to reset the found header address value before looping to another sheet? Thank you in advance.
Sub FindInDynamicRanges()

Dim wb1 As Workbook
Dim ws As Worksheet
Dim FoundCell, FoundTab, TabEntries As Excel.Range
Dim FirstAddr As String
Dim FirstRow, LastRow As Long

Set wb1 = ThisWorkbook

'Find all occurences of any table value on all sheets in dynamic ranges
For Each ws In wb1.Worksheets
    Set ws = ActiveSheet

    'Find "Header" cell
    Set FoundCell = ws.Columns(2).Find(What:="Header", LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByRows, _
SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)
    MsgBox FoundCell.Address

    'Set number of first entry row and last entry row
    FirstRow = FoundCell.Row + 1
    LastRow = ws.Cells.Find(What:="*", After:=Range("A1"), LookAt:=xlPart, LookIn:=xlValues, SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, MatchCase:=False).Row

    ws.Range("B" & FirstRow & ":B" & LastRow).Name = "TabEntries"
    MsgBox Range("TabEntries").Address

    With ws.Range("TabEntries")
        Set LastCell = .Cells(.Cells.Count)
    End With

    Set FoundTab = ws.Range("TabEntries").Find(What:="*", After:=LastCell, LookIn:=xlValues, LookAt:=xlWhole, _
SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)

    If Not FoundTab Is Nothing Then
        FirstAddr = FoundTab.Address
    End If

    Do Until FoundTab Is Nothing
            'do some staff with found values

        Set FoundTab = ws.Range("TabEntries").FindNext(After:=FoundTab)

        If FoundTab.Address = FirstAddr Then
            Exit Do
        End If
    Loop
Next ws

End Sub

A:
as it keeps found address of "Header" cell from the first sheet for every other sheet.

That is because you are telling it to...
For Each ws In wb1.Worksheets
    Set ws = ActiveSheet

You don't need that Set ws = ActiveSheet
When you say For Each ws, the ws is automatically initialized. So just remove the second line.


text:
Q: A non-numeric value encountered laravel i am passing values to print pdf in laravel controller . In local machine it works perfectly, but in live server it shows the "A non-numeric value encountered" error.
I using barrvdh dom pdf to print pdf

A: This is an issue when running Dompdf versions < 0.8.0 on a system that uses PHP 7.1 or greater. Most of the issues non-numeric errors were cleared up in 0.8.0. A few more were cleaned up for 0.8.1 (not yet released as of this posting).
Make sure you're using Laravel-Dompdf version 0.8.0 or higher (releases).

A: I had the same issue and fixed by following solution into "cellmap.cls.php" on line 436
/**Old Code:**/

// Determine where this cell is going
$colspan = $node->getAttribute("colspan");
$rowspan = $node->getAttribute("rowspan");

if ( !$colspan ) {
   $colspan = 1;
   $node->setAttribute("colspan",1);
}

if ( !$rowspan ) {
    $rowspan = 1;
    $node->setAttribute("rowspan",1);
}

/**New Code:**/

if(method_exists($node,'getAttribute')){
    // Determine where this cell is going
    $colspan = $node->getAttribute("colspan");
    $rowspan = $node->getAttribute("rowspan");

    if ( !$colspan ) {
       $colspan = 1;
       $node->setAttribute("colspan",1);
    }

    if ( !$rowspan ) {
        $rowspan = 1;
        $node->setAttribute("rowspan",1);
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Установка темной темы в приложении на Android. Android Studio Есть разметка(activity_main.xml):
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
    android:id="@+id/BtnMain"
    android:text="@string/BtnLight"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="132dp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.498"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="124dp"
    android:text="@string/sentence"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/BtnMain" />

</androidx.constraintlayout.widget.ConstraintLayout>

Код приложения:
public class MainActivity extends AppCompatActivity {
private final String TAG = "MainActivity";
private Button button;

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

    button = findViewById(R.id.BtnMain);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (button.getText().toString().equals("LIGHT") && AppCompatDelegate.getDefaultNightMode() == AppCompatDelegate.MODE_NIGHT_YES) {
                setTheme(AppCompatDelegate.MODE_NIGHT_YES);
                button.setText(R.string.BtnDark);
            }
            else {
                setTheme(AppCompatDelegate.MODE_NIGHT_NO);
                button.setText(R.string.BtnLight);
            }
            Log.d(TAG, "changed!");
        }
    });
}

}
Я хочу чтобы при нажатии кнопки тема переключалась со светлой темы на темную, и наоборот. Как это сделать? Я пробовал следующий код из моего Listener. Log выводится, но вот тема не меняется...

A: Переключать темы с дневной на ночную можно с помощью обращения к AppCompatDelegate:

*

*Чтобы включить ночную тему:
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)

*Чтобы переключить обратно на дневную тему:
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)

Метод setTheme() работает в тех случаях, когда он вызывается после метода super, и перед setContentView() в методе onCreate().


text:
Q: Consider all linear systems with exactly one eigenvalue equal to 0. Which of these systems are conjugate? This question considers non-hyperbolic matrices (2x2), which is not covered in our textbook.  Basically the problem I think tries to get us to think about conjugacy patterns of these cases, but I am stuck.
If A= ((a, b), (c, d)) a 2x2 has 1 eigenvalue = 0, then I believe c or b must be 0.
So A = ((a, 0), (c, d)) or ((a, b), (0, d)), but I'm not sure where to go from there.

A: This means that the matrix has rank 1 or one row is a multiple of another row and one row is non zero. Formally$$k_1(a,b)+k_2(c,d)=0$$and $$a^2+b^2+c^2+d^2\ne 0$$


text:
Q: Convert a .ogg blob into a google drive file Background
I want to record students speaking and then upload their recordings automatically to Google drive.
Current state of affairs
I have client side code which can produce a blob containing .ogg recording.
var blob = new Blob(chunks, { 'type' : 'audio/ogg; codecs=opus' });

I can send the blob to a Google apps script standalone script in a doPost() request. In this case I'm using axios with a promise.
axios.post("https://script.google.com/macros/s/SOME_ID/exec", blob)
  .then((response)=>{
   console.log(response)
  }).catch(error =>{
   console.log(error)
  })

The blob arrives at the standalone script.
The standalone Google apps script
function doPost(e) {

  var params = JSON.stringify(e.parameters);
  createNewSoundFile(params)
  return ContentService.createTextOutput(params);
}

function createNewSoundFile(blob){
  var title = 'Was created from a recording'
  var folderId = 'SOME_FOLDER_ID'
  var resource = {
    title: title,
    parents: [
      {
        "id": folderId,
        "kind": "drive#fileLink"
      }
    ],
    mimeType: 'application/vnd.google-apps.audio',
  };
  try{

  var newfile = Drive.Files.insert(resource, blob).id

  } catch(e){
   // Send error to Google sheet
   // Exception: The mediaData parameter only supports blob types for uploads.

  }
}

Problem
The above apps script code says the blob is not a support media type.
Question
How can I create become a new .ogg file in the Google drive from a .ogg blob created in the browser?

A: How about these modifications?
Modification points :
javascript side :

*

*Encode blob to base64, and sent it as the string data.

GAS side :

*

*Decode base64 to blob, and save it as a ogg file with the mimeType of audio/ogg.

*Save the file as audio/ogg.

*

*In my environment, it couldn't convert from audio/ogg to application/vnd.google-apps.audio.

Modified script : javascript side
From :
axios.post("https://script.google.com/macros/s/SOME_ID/exec", blob)
  .then((response)=>{
   console.log(response)
  }).catch(error =>{
   console.log(error)
  })

To :
var reader = new FileReader();
reader.readAsDataURL(blob);
reader.onloadend = function() {
  base64 = reader.result.replace(/^.*,/, "");
  let data = new URLSearchParams();
  data.append('data', base64);
  axios.post(
    "https://script.google.com/macros/s/SOME_ID/exec",
    data,
    {headers: {'Content-Type': 'application/x-www-form-urlencoded'}}
  ).then((response)=>{
    console.log(response)
  }).catch(error =>{
    console.log(error)
  });
}

Modified script : GAS side
To :
function createNewSoundFile(base64){
  var data = Utilities.base64Decode(base64.parameters.data); // Added
  var blob = Utilities.newBlob(data); // Added

  var title = 'Was created from a recording'
  var folderId = 'SOME_FOLDER_ID'
  var resource = {
    title: title,
    parents: [
      {
        "id": folderId,
//        "kind": "drive#fileLink" // I didn't know whether this is required.
      }
    ],
    mimeType: "audio/ogg", // Modified
  };
  try{

  var newfile = Drive.Files.insert(resource, blob).id

  } catch(e){
   // Send error to Google sheet
   // Exception: The mediaData parameter only supports blob types for uploads.

  }
}

Note :

*

*In my environment, {headers: {'Content-Type': 'application/x-www-form-urlencoded'}} was required for the script of javascript side. If it is not required in your environment, please remove it.

If I misunderstand your question, I'm sorry.


text:
Q: Write commande ESC/POS with Bluetooth thermal printer I try to change the Default code page into PC858 (Multilanguage + Euro) for print the Symbol € .
But any ESC/POS command work.
So i try to send hex value of command :
    public void EnvoiCommande(byte donnee)
    {
        byte[] array = {donnee};
        _outStream.Write(array, 0, 1);
        _outStream.Flush();
    }

    public void ImpressionTicket(List<string> donnee, string appareil, Texture2D logo)
    {
      // Code Page
      EnvoiCommande(0x1b);
      EnvoiCommande(0x74);
      EnvoiCommande(0x13);

      foreach (var txt in donnee)
      {
         var ligne = txt;
         Encoding encoding = Console.OutputEncoding;
         byte[] originalBytes = encoding.GetBytes(ligne);
         byte[] outputBytes = Encoding.Convert(encoding,
         Encoding.GetEncoding("CP00858"), originalBytes);
         _outStream.Write(outputBytes, 0, outputBytes.Length);
         Thread.Sleep(10);
      }
    }

All of my text is print correctly but my symbol € don't work.
Thank in advance for your help, i have try many PDF, And test many similar questions about that, but anything don't work.

A: Encoding.GetEncoding returns a value which you must use.

A: Have you tried to just send the bytecode for € to see if you have the correct code page?
https://en.wikipedia.org/wiki/Code_page_858
if you try to print 0xD5 and you get the € symbol then yes, you have the correct code page.
Then we know that the problem is when you convert the String to byteArray, check this out:
http://www.fileformat.info/info/unicode/char/20ac/index.htm
€ in unicode is: 0x20AC which is 0xE2 0x82 0xAC. So the € symbol transforms into 3 bytes that have other meaning for your printer. The printer prints this "Ôé¼" maybe?
If you only have trouble with the € symbols you can simply check the String before converting it to byte[].
if (ligne.contains("€"){
    ligne.replace("€",(char)0xD5);
}

A: Send the "Character Table command" in one flush:
public void EnvoiCommande(params byte[] donnees)
{
   _outStream.Write(donnees, 0, 1);
   _outStream.Flush();
}

// Code Page
EnvoiCommande(0x1b, 0x74; 0x13);


text:
Q: pymongo default database connection I need to connect to MongoDB from my Python code, the only thing I have is a url. Per mongo URL doc I can specify database name:
mongodb://host/db_name

Now I would like to use exactly database specified from URL and don't want to parse it manually to extract name of database. But MongoClient have no interface to access default one. Any thoughts how to manage this?

A: You can use pymongo.uri_parser.parse_uri for this:
Python 2.7.5 (default, Jul 12 2013, 14:44:36)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> uri = "mongodb://user:pass@example.com/my_database/?w=2"
>>> from pymongo.uri_parser import parse_uri
>>> parse_uri(uri)
{'username': 'user', 'nodelist': [('example.com', 27017)], 'database': 'my_database/',
'collection': None, 'password': 'pass', 'options': {'w': 2}}

In PyMongo 2.6 there will be a get_default_database() method for this. See PYTHON-461

A: PyMongo/MongoClient provides a get_default_database() method:
from pymongo import MongoClient

client = MongoClient("mongodb://host/db_name")
db = client.get_default_database()

https://pymongo.readthedocs.io/en/stable/api/pymongo/mongo_client.html

A: I got this error from Dan's answer:
OperationFailure: Authentication failed., full error: {'ok': 0.0, 'errmsg': 'Authentication failed.', 'code': 18, 'codeName': 'AuthenticationFailed'}

Solution
I realized I needed to specify the authentication source as there is authentication to my instance. If you face the same, use this:
from pymongo import MongoClient

client = MongoClient("mongodb://<USERNAME>:<PASSWORD>@<HOST>/<DEFAULT_DATABASE>?authSource=admin")
db = client.get_default_database()

# Then you may query
db["my_col"].find_one({})

Fill <USERNAME>, <PASSWORD>, <HOST>, <DEFAULT_DATABASE> accordingly (read more about MongoDB connection strings).
You may have the authSource in another database but I think admin is the default.

A: Looks like it doesn't work at all. When starting  pymongo dumps warning:

UserWarning: database name or authSource in URI is being ignored.


text:
Q: cgo **char to slice string I have developed a pam module using the cgo.
can not be converted to []string a ** char

func pam_sm_authenticate(pamh *C.pam_handle_t, flags C.int, argc C.int, argv **C.char) int {
        fmt.Println(C.GoString(*argv[0]))
        return 0
}

error is

invalid operation: argv[0] (type **C.char does not support indexing)

Please let me know if you know.

A: Cobbled together from the cgo wiki: https://github.com/golang/go/wiki/cgo#Turning_C_arrays_into_Go_slices.
import "C"
import "unsafe"

func GoStrings(argc C.int, argv **C.char) []string {

    length := int(argc)
    tmpslice := (*[1 << 30]*C.char)(unsafe.Pointer(argv))[:length:length]
    gostrings := make([]string, length)
    for i, s := range tmpslice {
        gostrings[i] = C.GoString(s)
    }
    return gostrings
}


text:
Q: Get notification origin in windows 10 uwp? I'm writing a uwp app with notification listener and I'm trying to get the origin of a notification (like Google Chrome and the website it came from).
I tried using the AppInfo.DisplayInfo for a UserNotification but I can't get it to print the info, and I'm not sure if this is the right way to do this.
IReadOnlyList<UserNotification> notifs = await MainPage.listener.GetNotificationsAsync(Windows.UI.Notifications.NotificationKinds.Toast);
UserNotification n = notifs.Last();
var name = n.AppInfo.DisplayInfo.DisplayName;

I expected name to be the name of the app the notification came from but it seems to be empty or just not working. To be precise from a notification like this:

I want to extract the "Google Chrome" and / or "www.reddit.com".

A: Hopefully you have found a solution by now, but in case this helps anyone:
The notification doesn't know that your message is coming from a browser. The whole Windows notifications system doesn't take that into an account. Windows receives a UserNotification from an application, which in your case happens to be a browser. So your "origin" is the application "Google Chrome". Your best shot is to try and get the link from inside the notification itself, if it is inside the body somewhere.
I really think you should be able to find the link inside the text of the notification, but I would need more information on what exactly you are receiving to be sure. If you want to know how to read the text of the notification, do:
string appName = notif.AppInfo.DisplayInfo.DisplayName; //this will get you "Google Chrome"
NotificationBinding toastBinding = notif.Notification.Visual.GetBinding(KnownNotificationBindings.ToastGeneric);

if (toastBinding != null)
{
    IReadOnlyList<AdaptiveNotificationText> textElements = toastBinding.GetTextElements();
    string titleText = textElements.FirstOrDefault()?.Text;
    string bodyText = string.Join("\n", textElements.Skip(1).Select(t => t.Text));
    string website = ParseWebsiteFromText(bodyText); //my guess is the info you want is in here
}

From there you have to parse the information you want, if it's available.
If you want to know more, I suggest reading the documentation from here: https://learn.microsoft.com/en-us/windows/uwp/design/shell/tiles-and-notifications/notification-listener.


text:
Q: Not able to generate local database file. I am using Visual Studio 2010 in which want to create a local DB file in my project.
When I register using the pre-built login, Visual Studio should create the DB file, but instead it shows a message box saying

Failed to generate a user instance of SQL Server due to a failure in starting the process for the user instance. The connection will be closed.

When i try to add it manually it shows the same message.
What can be done to resolve this issue?

A: Check your connection string on your App.Config file if its Correct.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>

  <connectionStrings>
    <add name="DB" connectionString="Data Source=MyPC\SQLEXPRESS;Initial Catalog=IIQR;Integrated Security=True"providerName="System.Data.SqlClient"/>
  </connectionStrings>

</configuration>

A: There are two solutions for this
1. Delete the following directory:
C:\Documents and Settings\username\Local Settings\Application Data\Microsoft\Microsoft SQL Server Data\SQLEXPRESS
2.. If that didn't work, then go to Control Panel -> Administrative Tools -> Services, right click on SQL Server (SQLEXPRESS) and go to Properties.  Go to the Log On tab and then select Local System account as the option.
The first option (deleting SQLEXPRESS) did not work for me but the second one did.


text:
Q: Scrape QS university world ranking (AJAX) I am trying to scrape QS university ranking data by analyzing Ajax interface as the QS global university ranking page is loaded through Ajax. However, I encounter couple of errors when compiling. In this case; I am getting a keyerror type: KeyError: 'url'.
url = 'https://www.topuniversities.com/sites/default/files/qs-rankings-data/en/3740566.txt?1624879808?v=1625562924528'
headers = {"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 "
                         "Safari/537.36"}
path = 'C:/Users/DELL/PycharmProjects/scrapeQS/qs-rank.txt'

def get_page(url):
    try:
        r = requests.get(url, headers=headers)
        if r.status_code == 200:
            return r.json()
    except requests.ConnectionError as e:
        print(e)

def parser_page(json):
    if json:
        items = json.get('data')
        for i in range(len(items)):
            item = items[i]
            qsrank = {}
            if "=" in item['rank_display']:
                rk_str = str(item['rank_display']).split('=')[-1]
                qsrank['rank_display'] = rk_str
            else:
                qsrank['rank_display'] = item['rank_display']
                qsrank['title'] = item['title']
                qsrank['region'] = item['region']
                qsrank['score'] = item['score']
                qsrank['url'] = item['url']
            yield qsrank

def main():
    json = get_page(url)
    results = parser_page(json)
    for result in results:
        with open(path, 'a') as f:
            f.write(result['rank_display'] + '    ' + result['title'] + '    ' + result['region'] + '    '
                    + result['score'] + '    ' + 'https://www.topuniversities.com' + result['url'] + '\n')
            f.close()
            print(result)

if __name__ == '__main__':
    print('Started parsing!')
    with open(path, 'a') as f:
        f.write('Ranking' + '    ' + 'University' + '    ' + 'Country' + '    ' + 'QS score' + '    ' + 'Link' + '\n')
        f.close()
    main()
    print('Done')

A: Well.. there is no 'url' in the data.
What make you think there is such key?
Example
   {
      "core_id": "624",
      "country": "Italy",
      "city": "Trieste",
      "guide": "",
      "nid": "297237",
      "title": "
University of Trieste<\/a><\/div>",
      "logo": "\/sites\/default\/files\/university-of-trieste_624_small.jpg",
      "score": "",
      "rank_display": "651-700",
      "region": "Europe",
      "stars": "",
      "recm": "0--"
    },


text:
Q: React - Passing data to Grand parent Component
As above structures , I would like to pass some states to "Left Components" which is Grand-Grand-Grand parent components.
 var grandChildRight = React.createClass({
      clicksomething : function () {
         this.setState({data:'you clicked me'});
      }
});

var leftComponent : React.createClass({
     render : function () {
         {this.props.data}
     };
 });

HTML

 <leftComponent data="?" />

<rightComponent>
   <anotherComponent>
        <grandChildRight />
    </anotherComponent>
</rightCompoent>

Is any way I can do this without using "Flux" or "Redux".
Please help me out this.
Thanks lot.

A: There should be a Parent Component above all of this then GrandChildRight Component will let Parent Component about any change then Parent Component will tell Left Component about the change
var Parent = React.createClass({
     handleEventChange : function(event){
         this.setState({data:event.data})
     },
     render : function () {
         <LeftComponent data={this.state.data}/>
         <RightComponent onEventChange={this.handleEventChange}/>

     };
});

var LeftComponent = React.createClass({
     render : function () {

{this.props.data}

     };
});

var RightComponent = React.createClass({
     render : function () {
         <GrandChildRightComponent onChildChange={this.handleChildEvent}/>
     };
     handleChildEvent : function (event) {
         this.props.onEventChange({data: event.data})
     };

});

var GrandChildRightComponent = React.createClass({
      clicksomething : function () {
         this.props.onChildChange({data:'Grand child is clicked'})
      }
});

A: You could try adding container that wraps your HTML and adding a callback prop to grandChildRight for it to call when its state updates:
var grandChildRight = React.createClass({
    clicksomething: function () {
        this.props.onUpdate({data:'you clicked me'});
    }
});

var leftComponent = React.createClass({
    render : function () {
        {this.props.data}
    };
});

var container = React.createClass({
    onRightGrandChildUpdate: function( newState ) {
       this.setState(newState);
    },

    render: function() {
        return (

             <leftComponent data={this.state.data} />

            <rightComponent>
              <anotherComponent>
                <grandChildRight onUpdate={this.onRightGrandChildUpdate.bind(this)} />
              </anotherComponent>
            </rightCompoent>

);
    }
});

(Notice the .bind(this) when passing this.onRightGrandChildUpdate to onUpdate of the grandChildRight component. Doing so ensures this binds to the container component, and not the current global object.)
Then your "HTML" becomes:
<container />

Essentially, this lifts the data you're interested in to a level above both the right grandchild and left component. The supplied onUpdate property allows the right grandchild to update the container's state, which then affects the data passed into the left component.


text:
Q: Get properties values from an object generic list c# i am trying to get the values from the properties of my generic list but i get an error "T does not contain a definition for...."
 var values GetValues(Id);

 if (values != null)
        {
            CreateTable<Object>(values);
        }

/////
    private void CreateTable<T>(IList<T> array)
    {

        foreach (item in array)
        {
          //Problem is here **** when trying to get item.tag
         var text = new TextBox(){ Text = item.Tag , ID = item.TagID.ToString() };

        }

    }

How can make it work with generics? Appreciate any help

A: Why is it that you expect that an object of some arbitrary T type has a Tag and TagID property? Where are these properties defined? If they are defined on an interface, let's say
public interface IItem
{
    string Tag { get; }
    int TagID { get; }
}

then you don't need generics, you can redefine CreateTable as
private void CreateTable(IList<IITem> array)
{
    foreach (var item in array)
    {
        //Problem is here **** when trying to get item.tag
        var text = new TextBox(){ Text = item.Tag , ID = item.TagID.ToString() };
    }
}


text:
Q: Compile error with templates - no matching function for call I'm trying to convert a string to a number. For that, I found the following way:
#include <iostream>
#include <string>

template <typename T>
T stringToNumber(const std::string &s)
{
    std::stringstream ss(s);
    T result;
    return ss >> result ? result : 0;
}

int main()
{
    std::string a = "254";
    int b = stringToNumber(a);

    std::cout << b*2 << std::endl;
}

The problem is that I am getting the following error:

error: no matching function for call to 'stringToNumber(std::string&)'

May anyone tell me why I am getting such error and how to fix it?
Thank you in advance.

A: Try
int b = stringToNumber<int>(a);

Because the template type T can not be deduced from any of the parameters (in this case std::string) you need to explicitly define it.

A: You haven't supplied a template argument. Note that in C++11, you can use std::stoi:
std::string a = "254";
int b = std::stoi(a);


text:
Q: Verificar se um option já existe pra não repeti-lo Olá!
Tenho um problema talvez simples, mas não tô conseguindo pensar em qualquer maneira de resolvê-lo.
Tenho um banco de dados aonde tenho uma tabela de produtos nele. Nessa tabela, tem a coluna cor. Então, estou criando um filtro na hora de pesquisar os produtos no site e como não sei exatamente quais cores estão em estoque, fiz esse while para imprimir as options:
$sql =  "SELECT `cor` FROM `produtos`";
<select id='iCor' name='nCor'>
       <option value=''>Todos</option>";
       while($linha = $result->fetch_assoc()){
            $cor = $linha['cor'];
            echo"<option value='$cor'>$cor</option>";
       }`

Mas esse com essa forma se eu tenho registrado as seguintes cores: amarelo, verde, vermelho, amarelo, vai aparecer 2 options contendo a opção amarelo.
O que eu quero é que de alguma forma, seja verificado se já tem aquele option no select. Se tiver, não faz nada. Se não tiver, coloca a cor como novo option

A: Tenta usar essa consulta:
$sql =  "SELECT DISTINCT `cor` FROM `produtos`";


text:
Q: css background color only of text justify I want to set the background color only of a justified text
(like when the text is selected by the mouse)
I've tried with div,
or span inside div,
or p without margin,
or h1 display inline,
but no one of these solutions solved my problem.
I don't mean the ::selection pseudo, but the text background that is always displayed

I want exactly this:

Please help

Fiddle

A: You can try this
HTML

Lorem ipsum dolor sit amet

CSS
.bg {
    background-color:red;
    display:inline;
    padding: 1px 0
}

A: Set the background property to whatever color you'd like.
Updated JSFiddle.

A: you can try like this: DEMO
HTML:

Lorem ipsum dolor sit amet

CSS:
.bg {
    background-color:red;
    display:inline;
}

A: The desired appearance requires the use of an inline element, since that is the way to stop the background where the text ends. Since you also want justified text, which requires a block element, you need two elements: a span, containing all the text of the block, nested inside a div or p:

Lorem ipsum ... in futurum.

The you just set the background on the span element:
.CCC { background: red; color: yellow }

A: you can give like this
::selection {
    background: #ffb7b7; /* Safari */
    }
::-moz-selection {
    background: #ffb7b7; /* Firefox */
}

or
p::selection {
    background: #ffb7b7; /* Safari */
    }


text:
Q: Linux - GREP print a line with special characters I have a problem with grep command, I want all the lines that start with '<', but that is not the problem, when I create a new file with the result of this grep, some special characters are changed for hex symbols
Grep command
cat OriginalFile.txt | grep '^<' > NewFile.txt

Before Grep

After Grep

Is it a way to prevent this change?
File command
Diff its OriginalFile.txt
Grep its NewFile.txt


text:
Q: can't change view tag or stream name in clearcase explorer in linux I am not been able to change any parameters in clearcase GUI? Any suggestions how to fix it.
I want to give the view tag and stream name as I wanted but it is not allowing me to write or change anything in clearcase explorer.

A: A ClearCase Explorer is for the view, files and directories.
You cannot change the name of a view, through GUI.
You could follow the process describe in this IBM technote (rmtag, unregister, moving the view storage, register, mktag...).
But frankly, you would be better off creating a new one (with the same config spec, which means, for an UCM view, create a new UCM view referring to the same Stream)
A ClearCase Project Explorer is for all UCM metadata: pvobs, projects, streams, activity.
You cannot change an UCM name through the GUI (at least in 7.x, the ClearTeam 8.x interface could be more helpful).
But you can rename a stream easily enough through cleartool rename stream:aStream@\aPVob nameName.
However, I would then recommend to build a new view pointing on the new Stream (instead of resetting the config spec, with a cd /path/to/your/view; cleartool chstream --generate)


text:
Q: TCL recursively call procedure I'm a beginner at TCL and while trying to build the GCD algorithm I ran into some problems I'd like some help with:
how can I call a proc inside a proc recursively like so
proc Stein_GCD { { u  0 } { v  0 } } {
    if { $v == 0 } {
        puts "$u\t\t$v\t\t$v"
    }
    if { [expr { $v % 2 } && { $u % 2 } ] == 0 } {
        return [expr 2 * ${Stein_GCD 1 0} ]
    }
}
set a [Stein_GCD 2 2 ]
puts $a

as you can see, I made the proc to evaluate GCD(the code does not make any sense because I'm trying to solve an example issue), and I'm trying to recursively call the proc again to continue evaluating(notice that I made an if statement that can understand the Stein_GCD 1 0 call, yet the tcl 8.6.6 online EDA emulator says:

can't read "Stein_GCD 1 0": no such variable
    while executing
"expr 2 * ${Stein_GCD 1 0} "
    (procedure "Stein_GCD" line 5)
    invoked from within
"Stein_GCD 2 2 "
    invoked from within
"set a [Stein_GCD 2 2 ]"
    (file "main.tcl" line 7)

Can you tell me how to efficiently recursively call a proc, and where was my mistake?
will gladly provide more info in the case I did a bad job at explaining.

A: The error can't read "Stein_GCD 1 0": indicates that you are treating the data as a single string instead of separate arguments.  The problem line:
 return [expr 2 * ${Stein_GCD 1 0} ]

is not written correctly.  ${Stean_GCD 1 0} is not a variable.
You should have:
 return [expr 2 * [Stein_GCD 1 0] ]

You want the result from Stein_GCD 1 0, so the brackets should be used.


text:
Q: how to check duplicate value in form before insert into database
I would like to check duplicate data when i insert duplicate in textbox it will display duplicate and I tried to insert not duplicate it display "Trying to get property of non-object"
Controller

public function gamecheck(){
    $this->load->library('form_validation'); // load from validation
    $this->form_validation->set_rules('gamename', 'Checkgamename', 'required');
    if ($this->form_validation->run() == TRUE) {
    if($this->input->post()) {
        $this->load->model('game_m');
        $gamepost = $this->input->post('gamename');
        $getgame = $this->game_m->get_game($gamepost);

           if($getgame->gamename!==''){
            echo "duplicate";
           }else{
            echo "not duplicate";
           }
         }
      }
    $this->load->view('header');
    $this->load->view('menu');
    $this->load->view('game/gamecheck');
    $this->load->view('footer');
}

Model

class Game_m extends CI_model{
public function get_game($gamepost) {
     $this->db->from('game');
     $this->db->where('gamename',$gamepost);
     return $this->db->get()->row();
    }
}

A: for unique value you can use is_unique[] in codeigniter like below
$this->form_validation->set_rules('fieldname', 'Msg you want to show', 'required|is_unique[table.coloum]');

A: for unique value i am using is_unique[] in codeigniter.
$this->form_validation->set_rules('gamename', 'Field is required', 'required|is_unique[game.gamename]');


text:
Q: Extract single points of interest from OSM when described both as nodes and ways I extracted both nodes and ways from OpenStreetMap in PostgreSQL with Osmosis. I'm looking for all restaurants in a given area. The issue is that some of them are coded in OSM as nodes and others as ways.
How is it possible to have only one point when it is represented both as a node and a way?
The intuitive answer is to intersect the ways with the nodes. If a node is inside a way, they will both count as one. Otherwise, if there is only a node or only a way without nodes inside, it's fine.
The 'geometry' column in the 'ways' table does not contain information (it has something like a geometry, but all values are similar). Or maybe it is possible to use the 'nodes' table?
The fundamental question is: How is it possible to have a proper geometry column in PostgreSQL with Osmosis?


text:
Q: i cant find this integral $\int_0^1 x^{-x} \mathrm{dx}$ $$\int_0^1 x^{-x} \mathrm{dx} $$

A: Hint:
$$\int_0^1{x^{-x}dx} = \int_0^1{e^{\log x^{-x}}dx} = \int_0^1{\sum_{k=1}^{\infty}\frac{(-x)^k\log^k x}{k!}}dx=  \sum_{k=0}^\infty \frac{1}{k!}\int_0^1 (-1)^kx^k(\log x)^k\,dx $$
for more detail see here how to integrate $\int\underbrace{x^{x^{\cdot^{\cdot^x}}}}_ndx$

A: The value is approximately 1.29129, as shown in this link:
http://www.wolframalpha.com/input/?i=definite+integral+of+x^%28-x%29+from+0+to+1

A: It's equal to 1 + 1/4 + 1/27 + 1/64 + .... +1/n^n ...


text:
Q: Partial String on Jinja2 String Variable to EntryField
Alright, I am a bit stumped by this.
I only get the first word, the space escapes I can't get the whole string. It prints to my log just fine, but when I use {{ project_company|safe }} in jinja, I get the first word only. I've looked at documentation and on stackoverflow unable to find an answer to this. I'm guessing its an easy fix and I'm formulating the question wrong.
Record sample: NORTHERN LIGHTS WEB SITE DEVELOPMENT/THE NORTHERN LIGHTS ENDEAVORS/KAREN/SWEENEY/ksweeney@northernlights.com
Example Company: THE NORTHERN LIGHTS ENDEAVORS
Result Company: THE

if request.method == "POST":
        req = request.form

    if str(req.get("select1")) == 'Project':
            mcon = pyodbc.connect('DRIVER={SQL Server};SERVER='+mserver+';DATABASE='+cwdatabase+';UID='+musername+';PWD='+mpassword)
            m = mcon.cursor()
            m.execute(project_query, str(req.get("entry0")))
            mprecords = m.fetchall()

        for record in mprecords:
                project_number = req.get("entry0")
                project_summary = record[1]
                project_company = str(record[2])
                project_name = str(str(record[3]) + ' ' + str(record[4]))
                project_mail = str(record[5])

        return render_template('salesconfirm.html',
                                project_number=project_number,
                                project_summary=project_summary,
                                project_company=project_company,
                                project_name=project_name,
                                project_mail=project_mail)
__________________________________________________________________

          <label for="formGroupExampleInput">Company</label>
          <input class="form-control" type="text" placeholder={{ project_company|safe }} readonly>

Log Printout format:
output.writelines(str(datetime.now()) + ' - Project Info: ' + str(record[1]) + '/' + str(record[2]) + '/' + str(record[3]) + '/' + str(record[4]) + '/' + str(record[5]) + "\n")

Log Output:
2020-06-05 09:21:29.214032 - Project Info: NORTHERN LIGHTS WEB SITE

DEVELOPMENT/THE NORTHERN LIGHTS ENDEAVORS/KAREN/SWEENEY/ksweeney@northernlights.com

A: Well, it was quite easy.
Adding quotes before and after the variable in Jinja fixes it
<input class="form-control" type="text" placeholder="{{ project_company|safe }}" readonly>


text:
Q: How to modify the html file content in jsoup? I Have a html file like below

 s

I want to modify like this using java

 Test

is it possible  in jsoup ?

A: it is posible:
  Element el = doc.select("div#test").first();
  for (Element elC : el.children()) {
      elC.remove();
  }
  Element nel = el.appendElement("b");
  nel.text("Test");


text:
Q: When is "session" argument necessary in R shiny server function? I am very new to Shiny and I have gone through all the tutorials on the Rstudio website, and have run and tested example apps myself.
I noticed that in Joe Cheng's reactivity videos he always puts session as an argument in the server function like this:
server <- function(input, output, session) {}

while in most of the other examples I see
server <- function(input, output) {}

I know that the session argument is optional, but I wonder whether there is a situation where it is absolutely needed. What is the difference with or without the session argument?
I could not find an explanation anywhere else.


text:
Q: Changing LaF based on OS Im building a GUI in Netbeans, it looks good in the designer but when I run the program it looks pretty rubbish. Im using a Mac and so I feel that it would look better using the Mac OS LAF but then when I run it on Windows, what will happen? Is a Windows system able to use the Mac LAF and vice-versa?
I dont usually mind the Ocean/Metal LAF but it looks better on Windows than it does on Mac, is there a way to set a theme as a fallback? Or to change depending on the system its running on?

A: The UIManager.setLookAndFeel(String className) Loads the LookAndFeel specified by the given class name:className, using the current thread's context class loader.
To set look and feel of your current system, make use of UIManager.getSystemLookAndFeelClassName(): Returns the name of the LookAndFeel class that implements the native system look and feel if there is one, otherwise the name of the default cross platform LookAndFeel class.
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

put this code before you create instance of your application window: JFrame or any such Top-level Container.


text:
Q: switch context in C I am learning how to use ucontext_t in C, and have written the following code. I wish to use an infinite while loop to watch the switching between two contexts (ctx_main, and ctx_thread). But, the context seems to be stuck in the while loop. I am looking for some help with correcting the code. I put my comments in the code below:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ucontext.h>

#define MEM 64000

ucontext_t ctx_main, ctx_thread;
static int thread_id = 0;

/* the function thread_init() will initialize the ctx_main context
*  this is the first function to be called in main() */

void thread_init()
{
    getcontext(&ctx_main);
    ctx_main.uc_link = 0;
    ctx_main.uc_stack.ss_sp = malloc(MEM);
    ctx_main.uc_stack.ss_size = MEM;
    ctx_main.uc_stack.ss_flags = 0;

    printf("printed in thread_init()\n");
}

/* This function revert_main is supposed to increment the global variable thread_id,
*  then switch back to ctx_main context */

void *revert_main(void *n)
{
    thread_id += *(int *) n;
    printf("printed in the revert_main()\n");
    swapcontext(&ctx_thread, &ctx_main); /* now switch back to ctx_main context */
}

int main()
{
    thread_init();   /* Initialize the ctx_main context */

    getcontext(&ctx_thread);  /* Initialize the ctx_thread context */

    ctx_thread.uc_link = 0;
    ctx_thread.uc_stack.ss_sp = malloc(MEM);
    ctx_thread.uc_stack.ss_size = MEM;
    ctx_thread.uc_stack.ss_flags = 0;

    int *j = (int *) malloc(sizeof(int));
    *j = 1;
    while(1)  /* Infinite loop to switch between ctx_main and ctx_thread */
    {
        printf("printed in the main while loop\n");

        printf("the thread id is %d\n", thread_id);
        makecontext(&ctx_thread, (void *)&revert_main, 1, (void *)j);  /* hopefully this will trigger the revert_main() function */
    }

    return 0;
}

A: Your main routine sets up a new context, but never switches to it, so revert_main never runs.
You only want to call makecontext once for a give u_context object.  So move the call to makecontext out of the loop.


text:
Q: Restlet: Retrieving http body in verifier When I want retrieve the http body of a post in my Request Verifier it kinda resets my entity and I get a nullpointer exception when I want to get the http body in my resource class.
Verifier:
JsonRepresentation jsonrep;
        try {
            Representation entity = request.getEntity();
            jsonrep = new JsonRepresentation(entity);
            //bug: entity resets when getJsonObject is being called.
            JSONObject jsonobj = jsonrep.getJsonObject();
            if(companyId != jsonobj.getInt("id_companies")){
                return Verifier.RESULT_INVALID;
            }
...

AppResource:
@Post
public Representation addApp(Representation rep) throws Exception{
//rep is null
    JsonRepresentation jsonrep = new JsonRepresentation(rep);

When I dont't call:
                JSONObject jsonobj = jsonrep.getJsonObject();

it  just works fine.
Is anybody facing the same issue or got a solution for it?
Thanks in advance!

A: In fact, by default, the representation is an InputRepresentation that doesn't store the representation content.
In your case, the simplest way is to wrap the representation into a StringRepresentation within your verifier:
Representation entity = request.getEntity();
StringRepresentation sEntity = new StringRepresentation(entity);
request.setEntity(sEntity);

JsonRepresentation jsonrep = new JsonRepresentation(sEntity);
Then, the string representation will be automatically provided to your server resource method...
Hope it helps you.
Thierry


text:
Q: PowerShell Copy-Item to remote - custom port I want to copy some file from local computer to remote in a standard way:
Copy-Item -Path C:\some_path\test.txt -Destination \\server\c$\some_other_path\test.txt

Unfortunately i have to specify custom port due to routing on server. I am pretty new to remote management and powershell. Is there any way to specify port for Copy-Item or UNC path? If not, are they some other reasonable solutions to this problem? Thanks in advance.

A: Even though this is an old thread, I still provide my method here hoping that could help someone else.
According to the official docs, there is no way to specify a port using Copy-Item, but you can try to use parameter ToSession to achieve your goal if your PS version is higher than 5, see the new features here.
Create a session with a specified port:
$session = New-PSSession -ComputerName $computer -Port $port

Then copy files using the session:
Copy-Item "C:\some_path\test.txt" -Destination "C:\some_other_path\test.txt" -ToSession $session

And don't forget to remove the session when
you're done.
$session | Remove-PSSession

Reference:
Use PowerShell Copy-Item to File Transfer Over WinRM


text:
Q: jQuery Mobile Header - How to repeat-x a bg and put an image on? I need to setup my header. I'm trying to repeat-x a background and put an image on with no luck.
HTML:

CSS:
    .ui-header{
    background-image: url(http://www.mybizonline.co.il/book/tno/jquery-mobile/images/bg.jpg);
    background-repeat: repeat-x;
    width: 1024px;
    height: 275px;
}

Its should look like this:

bg repeated to x, image on the bg
Does anyone have idea why it doesn't work?

A: html:

css:
#bg_wrapper {
    background: url('...') repeat-x;
    text-align: center;  // To center your img
}

A: You can apply the background-image to your img if you add
display: block
to the CSS but I would suggest applying the ui-header class to the div wrapping your image instead:
http://jsfiddle.net/8mv7V/

CSS:
.ui-header
{
background-image: url(http://www.mybizonline.co.il/book/tno/jquery-mobile/images/bg.jpg);
background-repeat: repeat-x;
height: 462px;
text-align: center;
}

(P.S. I think your background image, bg.jpg, might be 8px off at the top)

A: For this you have to do some work on image resizing, i have done what you are trying to do:
.ui-header{
   background: url(http://www.mybizonline.co.il/book/tno/jquery-mobile/images/bg.jpg) 0 -60px repeat-x;
   width:500px;
   height: 275px;
   padding:0 254px;
   text-align:center;
}

you can find out here: http://jsbin.com/aduxum/5/edit


text:
Q: Custom rule based on two value I have the following data model: Region (id, name, countries_id, tag). The tag is unique and it's composed of name + countries_id. For example:
name=Arizona
countries_id=us
tag=arizona-us

The name and countries_id values are attached in the request data but, tag value must be unique and is generated dinamically.
I want create a validation rule that validates the uniqueness property of tag value.
My code is:
return array(
    'name' => ['required', new RegionUniqueRule()],
    'countries_id' => ['required', 'exists:mysql.countries,id'],
);

class Regionunique implements Rule
{
    public function passes($attribute, $value)
    {
        $countriesIdValue = 'COUNTRIES_ID VALUE !!!';
        $text = sprintf('%s %s', $value, $countriesIdValue);
        $table = DB::table('regions');
        $table->where('tag', str_slug($text));
        return ($table->first() === null);
    }

    public function message()
    {
        return 'The region already exists';
    }
}

So, how i can get the countries_id value inside of Regionunique ?

A: What you can do is to create a input before validate, like this:
<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

abstract class Request extends FormRequest
{
    /**
     * Override Symfony\Component\HttpFoundation\Request::initialize.
     * After parent::initialize, run beforeValidation
     */
    public function initialize(array $query = array(), array $request = array(), array $attributes = array(), array $cookies = array(), array $files = array(), array $server = array(), $content = null)
    {
         parent::initialize($query, $request, $attributes, $cookies, $files, $server, $content);
         $this->beforeValidation();
    }

    protected function beforeValidation()
    {
         //implement in child class
    }
}

class MyRequest extends Request
{
    protected function beforeValidation()
    {
         $tag = sprintf('%s %s', $this->input('name'), $this->input('countries_id'));
         $this->merge([
             'tag' => $tag,
         ]);
    }

     public function rules()
     {
         return array(
              'name' => ['required'],
              'countries_id' => ['required', 'exists:mysql.countries,id'],
              'tag' => ['required','unique'],
         );
     }
}

class MyController
{
     public function myMethod(MyRequest $request)
     {
          //do something
     }
}

Here we create a new Request abstract class, that override initialize(..)  function from framework. After initialized, the base class call beforeValidation() to run anything before the validation. Then we insert a new input value tag to the input array, and validate against unique rule.


text:
Q: multer and csrf protection If I have an error with multer, for example an invalid file format, then the csrf protection would failed (invalid token).
That's because the csrf protection is configured after multer.
But csrf protection also fails if I add it before multer. I get : 'invalid csrf token'.
How can I throw a multer error, but with keeping the csrf protection ?
Below the error is thrown at cb('INVALID FILE!!!', false);, and caught by the express error-handling middleware. But the csrf token will be missing.
const csrfProtection = csrf();

const fileStorage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, 'images');
  },
  filename: (req, file, cb) => {
    cb(null, new Date().toISOString().replace(/:/g, '-') + '-' + file.originalname);
  }
});

const fileFilter = (req, file, cb) => {
  if (
    file.mimetype === 'image/png' ||
    file.mimetype === 'image/jpg' ||
    file.mimetype === 'image/jpeg'
  ) {
    cb(null, true);
  } else {
    cb('INVALID FILE!!!', false);
  }
};

app.set('view engine', 'ejs');
app.set('views', 'views');

const adminRoutes = require('./routes/admin');
const shopRoutes = require('./routes/shop');
const authRoutes = require('./routes/auth');

    app.use(bodyParser.urlencoded({ extended: false }));
    app.use(
      multer({ storage: fileStorage, fileFilter: fileFilter }).single('image')
    );

    app.use(express.static(path.join(__dirname, 'public')));
    app.use('/images', express.static(path.join(__dirname, 'images')));
    app.use(
      session({
        secret: 'my secret',
        resave: false,
        saveUninitialized: false,
        store: store
      })
    );
    app.use(csrfProtection);
    app.use(flash());

    app.use((req, res, next) => {
      res.locals.isAuthenticated = req.session.isLoggedIn;
      res.locals.csrfToken = req.csrfToken();
      next();
    });

    app.use((req, res, next) => {
      if (!req.session.user) {
        return next();
      }
      User.findById(req.session.user._id)
        .then(user => {
          if (!user) {
            return next();
          }
          req.user = user;
          next();
        })
        .catch(err => {
          next(new Error(err));
        });
    });

    app.use('/admin', adminRoutes);
    app.use(shopRoutes);
    app.use(authRoutes);

    app.get('/500', errorController.get500);

    app.use(errorController.get404);

    app.use((error, req, res, next) => {
      console.log(error);
      res.status(500).render('500', {
        pageTitle: 'Error!',
        path: '/500',
        isAuthenticated: req.session.isLoggedIn
      });
    });

In short :
Why can't I set up csrf protection before the multer ?
And if I really can't, how can I throw a multer error, and keep using csrf in my app ?

A: I have figured out all the explanations.
multer looks at each input in order. If there's an error in the image field (like my "invalid file" error), it will throw an error, but in my error handling middleware, my req.body will only contain the form data up to, but excluding, the image field.
That means I can move, in my form html, the hidden csrf input field anywhere before the image input field.
So now, when multer throws an error, I have access to the current csrf value with req.body._csrf . Note that in this case, I should not use req.csrfToken() in the error handling middleware, since that will set a new token to be used in the next rendered view. Here, it is a "post" route, so I need to use the csrf token that was first loaded in the html ("get" route).


text:
Q: How to redefine type for React class prop I´m using Avatar from react-native-elements and the ImageComponent prop is typed as React.ComponentClass (IntelliSense report type React.ComponentClass<{}, any>)
When using a functional component (with prop key) I get red squiggles under ImageComponent:
  <Avatar
    rounded
    size={c.styles.avatarSize}
    containerStyle={{ margin: c.styles.marginLRTB / 2 }}
    placeholderStyle={{ backgroundColor: colors.background }}
    ImageComponent={() => AvatarImage(key)}
  />

 Type '() => JSX.Element' is not assignable to type 'ComponentClass<{}, any>'.ts(2769)
AvatarImage:
  const AvatarImage = (key: string) => (
    <FastImage
      style={{ width: '100%', height: '100%' }}
      source={sourcesState[key].category === 'In-app' ? avatars[key as QuotesListKeys] : { uri: sourcesState[key].imageUrl }}
    />
  );

How can I fix this typescript error?
I´ve tried to define a new class/interface that extend Avatar/AvatarProps:
  type MyAvatarProps = Omit<AvatarProps, 'ImageComponent'> & { ImageComponent: FC<{ key: string }> };

  class MyAvatar extends Avatar<MyAvatarProps> {}

I get typescript error Type 'Avatar' is not generic.ts(2315)
How do I extend Avatar with MyAvatarProps when it's not generic?
Or is there other/better ways to handle this?
Update:
See my answer below

A: I got around the issue with a simple TS cast:
ImageComponent={((() => AvatarImage(key)) as unknown) as ComponentClass<{}, any>}


text:
Q: Change html table background color for dynamically added even rows I have the below sample html table definition.

                    Row#

                    Nationality

                    No of Visitors

                    Remarks

                      @if (Model.VisitDetails.Any())
                      {
                          foreach (var item in Model.VisitDetails)
                          {
                              @Html.Partial("VisitDetailsPartial", item);
                          }
                      }
                      else
                      {
                          item.RowId = 1;
                          item.NationalityList = ViewBag.NationalityList;
                          @Html.Partial("VisitDetailsPartial", item);
                      }

On the click of a button, the rows which are defined in asp.net MVC partial view are added to the table.
Button click
$(document).ready(function () {
        var tableBody = $('#myDynamicTableDiseases tbody');
        var url = '@Url.Action("Add", "Report")';
        $('.btnAddRow').click(function () {
            $.get(url, function (response) {
                tableBody.append(response);
                $('#myDynamicTableDiseases tbody tr').each(function (idx) {
                    $(this).children("td:eq(0)").html(idx + 1);
                });
            });
        });
    });

The "Add" action in "Report" control returns the "VisitDetailsPartial" as a new row added to the table.
Below is the VisitDetailsPartial definition.
 @model SolutionName.ViewModel.VisitDetailsViewModel

    @using (Html.BeginCollectionItem("item"))
    {

              @if (Model == null)
            {
                var item = new VisitDetailsViewModel
                {
                    NationalityList = ViewBag.NationalityList,
                };
                @Html.LabelFor(x => item.RowId, item.RowId.ToString(), new { style = "", @class = "autoGenNumber" })
            }
            else
            {
                @Html.LabelFor(x => Model.RowId, Model.RowId.ToString(), new { style = "", @class = "autoGenNumber" })
            }

            @Html.DropDownListFor(model => model.NationalityId, new SelectList(Model.NationalityList, "Value", "Text", Model.NationalityId), "Select", new { @id = "ddlNationalityList" })

            @Html.TextBox("txtNumberOfVisits", Model.NumberOfVisits, new { id = "txtNumberOfVisits"})

            @Html.TextBoxFor(x => Model.Remarks, new { id = "txtRemarks", Multiline = true})

    }

I'm trying to use the CSS below to change the background color in the first column of the dynamically added even table row but the CSS is not being applied.
.table-striped > tbody > tr:nth-of-type(even) td:first-child {
  background-color: #e0f0ff;

}
If i apply the same to a table in whose rows are NOT coming from a partial view, the CSS works fine.
Not sure what i'm missing above.

A: Ok, i got it working by modifying the CSS as below though in my markup above, i cant seem to see why i consider to be column 1 is actually being treated as column 2.
This version works.
    .table-striped > tbody > tr:nth-of-type(even) > td:nth-child(2) {
    background-color: #e0f0ff;
}


text:
Q: How can I use variables from a form globally in Laravel 8? I want to use a variables from a form globally but I don't know how do it with Laravel 8

For example, I want to write in "Alfabeto" a string like this: "a, b, c, d" and that when pressing "Confirmar" I can use this variable with the string "a, b, c, d" in any of the blade views.

Alfabeto
<input type="text" class="form-control" name="alfabetoAutomata" id="alfabetoAutomata" title="Debe ingresar el alfabeto como el siguiente ejemplo: a,b,c" pattern="^[a-zA-Z0-9]+(,[a-zA-Z0-9]+)*$" placeholder="Ingrese el alfabeto para los autómatas separados por comas. (Ej: a,b,c)" autocomplete="off" value="<?php echo htmlspecialchars($_GET['alfabetoAutomata'] ?? '', ENT_QUOTES); ?>" required>

I want to use the var $_GET['alfabetoAutomata'] globally, how I can do it?
I hope I have made myself understood, thank you very much!

A: Check out the View::share documentation. https://laravel.com/docs/8.x/views#sharing-data-with-all-views
If that is not what you are looking for, then I would suggest, inside your controller, set a session variable like this.
 Session::put('foo', 'bar')

Above foo is the name of the variable and bar is the value. Now, when I need to change the value of foo, for example in a blade file,  I can do so like this.
{{Session::put('foo','Another Bar')}}


text:
Q: OneTimeSetup doesnt seem to be finishing before other tests are ran I am currently trying to find an element on the webpage, but am getting an exception that it doesn't exist. I think this is happening, because the webpage doesn't get a change to load all the way before it starts looking for the element. I put a wait in my OneTimeSetUp setup() method, but that doesnt seem to be doing anything... All the tests seem to run before the wait is finished. Does anyone have any suggestions to where I would be able to ensure the webpage is loaded, before continuing on with the tests and trying to find elements?
My Current Setup() method:
//Executes before tests start
    //Open Homebanking URL and Login
    [OneTimeSetUp]
    public void Setup()
    {
        var _driver = DriverHelper.Driver;
        var driverHelper = new DriverHelper();
        _driver.Url = driverHelper.homebankingURL;
        driverHelper.maximizeWindow(_driver);

        var loginPage = new HomeBankingLoginPage();

        //Enters login credentials
        loginPage.UserName.SendKeys(usr);
        loginPage.Password.SendKeys(pwrd);
        loginPage.Submit.Click();

        //Lets the webpage load before continuing
        _driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(30);

        // Checks to make sure the dashboard loaded
        Assert.IsTrue(driverHelper.IsElementPresent(_driver, By.Id("SvgjsSvg1001")));

    }

A: I would recommend using Explicit waits here  :

Explicit waits are available to Selenium clients for imperative,
procedural languages. They allow your code to halt program execution,
or freeze the thread, until the condition you pass it resolves. The
condition is called with a certain frequency until the timeout of the
wait is elapsed. This means that for as long as the condition returns
a falsy value, it will keep trying and waiting.

WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
IWebElement firstResult = wait.Until(e => e.FindElement(By.Id("SvgjsSvg1001")));

and then you can assert as you like.
in case you need Official reference


text:
Q: What happens to the frequencies of added sound waves? What happens to the frequency when two sound waves add up to a complex wave?
Example: I play a G3 on the guitar at 196 hertz and at the same time on the piano
A4 440 hertz.
What would be the "total frequency"? ( if there is such a thing)
Very thankful for any information.

A: The waves do just 'add-up' their amplitudes, so that where two peaks combine you get a larger peak, where a peak combines with a trough the two amplitudes cancel, and where the two waves are both zero you get zero amplitude. Because the two waves have different frequencies, the alignment of their peaks and troughs varies over time in a way that isn't equal to either of their frequencies but is related to their relative values. You end up with a sound that has no well-defined frequency but seems to combine indictions of both the original frequencies plus a third effect that tends to be lower in frequency than either of the other two.
The effect depends on the relative amplitudes and frequencies of the two waves. You might find it easiest to get a mental picture if you imagine a few extreme cases. For example, consider a very low frequency wave with a large amplitude combined with a high frequency wave of small amplitude. The result will look like the original wave with tiny ripples on it. You can observe the effect on the surface of a large body of water in windy conditions when you can see long wavelength undulations with short wavelength ripples super-imposed.
An interesting effect occurs when you combine two sound waves with similar amplitudes. The alignment of their peaks and troughs varies from being almost exactly in phase to almost exactly out of phase over a time period that is equal to the difference between their frequencies, so you hear their two sounds overlaid by a periodic waxing and waning of volume known as 'beats'. If you know  what to listen for you can use the sound of the beats to tune two neighbouring guitar strings, fretting the lower string so that it should play the same note as the higher one. If you tune the strings slightly out at first and pluck them together you can hear the beat, and you can adjust the tension until the period of the beat gets longer and eventually disappears.
When the wavelength of one wave is an integer multiple of the other, or the two are in a simple ratio like 2:3 you tend to get an overall effect that is pleasing to the ear. Such ratios are known as harmonics. Generally, when you pluck a string on a guitar it does not vibrate purely at its nominal frequency, but in a complex pattern that is the superposition of a number of harmonics. If you pluck the string carefully at its mid point then the resulting motion is dominated largely by its nominal frequency, whereas if you pluck it near either end you will activate more overtones.

A: Good question!
When adding sinusoidal waves, there's a handy trig identity we can use
$$\sin(\alpha)+\sin(\beta)=2\cos(\frac{\alpha-\beta}{2})\sin(\frac{\alpha+\beta}{2})$$
So given that a standard sinusoidal wave can be expressed as
$$y=A\sin(kx-\omega t)$$
To add two waves of differing frequency (but the same amplitude and phase), we can take
$$y_1+y_2=A\sin\left(k_1x-\omega_1 t\right)+A\sin\left(k_2x-\omega_2 t\right)$$
$$\alpha=k_1x-\omega_1t \quad\quad\quad \beta=k_2x-\omega_2t$$
$$\alpha-\beta=\left(k_1-k_2\right)x-\left(\omega_1-\omega_2\right)t \quad\quad\quad \alpha+\beta=\left(k_1+k_2\right)x-\left(\omega_1+\omega_2\right)t$$
$$y_1+y_2=2A\cos\left(\frac{k_1-k_2}{2}x-\frac{\omega_1-\omega_2}{2}t\right) \sin\left(\frac{k_1+k_2}{2}x-\frac{\omega_1+\omega_2}{2}t\right)$$
This is where some lecture notes from RIT's Physics 207 really elegantly explain what's going on
$$\frac{a_1+a_2}{2}=a_{avg}$$
$$\frac{k_1+k_2}{2}=k_{avg} \quad\quad\quad \frac{\omega_1+\omega_2}{2}=\omega_{avg}$$
Which means that what we're really looking at is the following
$$y_1+y_2=2A\cos\left(\frac{\Delta k}{2}x-\frac{\Delta \omega}{2}t\right) \sin\left(k_{avg}x-\omega_{avg}t\right)$$
The sine term is just a wave of our original form $y=A\sin(kx-\omega t)$, but more specifically it's the average of our two waves.
The cosine term acts as a coefficient on the amplitude, causing the average wave from the sine term to increase and decrease with amplitude depending on the difference between our two components of wave speed $k$ and $\omega$.
Thus what we'd end up with is something like this (taken from the aforementioned RIT lecture notes):

Noteworthy is that it doesn't matter whether you interpret this as the high-frequency wave being given an amplitude equal to the $y$ value of the low-frequency wave at each point, or the low-frequency wave being given an amplitude equal to the $y$ value of the high-frequency wave at each point. The effect is the same. This corresponds to the commutative property of addition, which also applies to wave addition, and the commutative property of multiplication, which applies to the multiplied sine and cosine terms in the final equation. Either wave could be "bending" the other, and the effect would be the same.
If you want to consider waves that differ in phase, things get a bit more complicated, but I'm sure someone else would be more than happy to give details on that :)


text:
Q: mongoose.js: on building great schema's | nested vs reference I'm trying to get my head around the concepts of a great schema design for my database structure. Should i embed nested documents or should i use a reference?
I have this structure:
book
 | bookTitle
 | bookChapters
 | | chapterTitle
 | | chapterArticles
 | | | articleTitle
 | | | articleSubTitles
 | | | | title

I will be having multiple books with their chapters and articles. So i have 2 questions:

*

*how would my mongoose schema look like (1 schema vs multiple
schema's / embed vs reference)

*How would i query for instance all chapterTitles from bookTitle x

Thx for you help, i guess i'm almost ready to go on my own when i understand these fundamental concepts.

A: If that's the schema in your database, then you could use a mongoose schema like this:
var articleSubTitleSchema = new Schema({title: 'string'});
var articleSchema = new Schema({title: 'string', articleSubTitles: [articleSubTitleSchema]});
var chapterSchema = new Schema({title: 'string', chapterArticles: [articleSchema]});
var bookSchema = new Schema({title: 'string', 'bookChapters': [chapterSchema]});

Your best bet for part two is to simple fetch the entire book document, and get the chapters in application code.
var book = ... query ...
var chapters = book.bookChapters;
var chapterTitles = _.pluck(chapters, 'title');

Here I use http://underscorejs.org/ to make grabbing the titles a little easier.
If you wanted to search for all books with a particular chapter, you could write a query like: {'bookChapters.titles': '[title]'}

A: There is no developer who does not favor splitting up single documents in mongodb :) Unfortunately this is only nice in theoretical thoughts. Practically there is no support for this neither from mongodb nor from mongoose.
Sure there are support of references but believe me every approach in this direction is punished by a lot of time just invested for the result that there are too much negative side effects (population, extra saving, ...) then benefits in comparison if we save stuff extra.
This is my experience so far. Except you want to write an own layer on top of mongodb-native you will have a lot of pain trying to work with references.


text:
Q: Windows only refresh if click on title bar (12.04-VirtualBox) I am trying to install ubuntu 12.04 LTS in a VirtualBox running on Windows 7 Pro. I have followed the instruction posted in Why does a Ubuntu guest in VirtualBox run very, very slowly?
Unity 3D seems to be loading OK but all windows only update their content when I click on the window title bar. Even terminal, in terminal I can press return a few times and nothing updates until I click on the title bar, then I can see the expect responses.
My system -
VirtualBox (4.2.10 r84104)
Extension Pack 4.2.10
Ubuntu 12.04 LTS
Additions installed
I have

*

*Install VirtualBox Oracle VM VirtualBox Extension Pack.

*Create a VirtualBox instance and install Ubuntu 12.04 LTS on it.

*apt-get update

*apt-get upgrade

*apt-get install dkms

*Rebooted

*cd /media/VBOXADDITIONS_4.2.10_84104

*sudo ./VBoxLinuxAdditions.run

*Rebooted

*Add the vboxvideo driver to the instance by running:
sudo bash -c 'echo vboxvideo >> /etc/modules'

*Shutdown

*In my BIOS enabled "Intel Virtualization Technology"

*In Virtualbox set video memory 128MB and enable 3d acceleration

*Boot Ubuntu guest, and check that 3D acceleration is working by running:
/usr/lib/nux/unity_support_test -p
which returned
OpenGL vendor string:   Humper
OpenGL renderer string: Chromium
OpenGL version string: 2.1 Chromium 1.9

Not software rendered:    yes
NOT blacklisted:          yes
GLX fbconfig:             yes
GLX texture from pixmap:  yes
GL npot or rect textures: yes
GL vertex program:        yes
GL framebuffer object:    yes
GL version is 1.4+:       yes

Unity 3D supported:       yes

I have also installed and run CompizConfig Settings Manager but I can't find any framebuffer options. I think I just need to set some option somewhere but I have no idea where to look now.
P.S. Unity 2D works OK, but I would like to get Unity 3D working then I could try 12.10.

A: Seems like known issue of the VirtualBox running on hosts with NVidia adapters (https://www.virtualbox.org/ticket/2985)
There are 2 ways to resolve:
1) update host's video drivers
2) if it doesn't help, turn off "3D acceleration" in your virtual machine settings
Hope, it helps.

A: Contrary to Rom098's answer, I had to activate "3D acceleration" in my virtual machine settings in order to make it work.


text:
Q: Can a Maven BOM contain another Maven BOM? Can a Maven BOM(BOM1) contain another BOM(BOM2) in its dependencyManagement? If yes, how could the usage of BOM1 through inclusion in a pom.xml can use the dependencies from BOM2 in a project? Thanks in advance!
To better explain the situation, the below works when i include both of the in the pom.xml of the service:
<dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>${spring-boot-dependencies.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>my.custom.bom</groupId>
                <artifactId>my.custom.bom</artifactId>
                <version>${my.custom.bom.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
</dependencyManagement>

Whereas the following does notwhen I include it in the pom.xml of the service:
<dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>my.custom.bom</groupId>
                <artifactId>my.custom.bom</artifactId>
                <version>${my.custom.bom.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
</dependencyManagement>

And the my.custom.bom in the second situation includes the spring-boot-dependencies like so:
<dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>${spring-boot-dependencies.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
</dependencyManagement>

To summarize when pom.xml includes BOM1 and BOM2 works, but when pom.xml includes BOM1 and BOM1 includes BOM2 no longer works.


text:
Q: Plural of numbers (as nouns) I really tried to find an answer in Internet but turns out I've found two different answers for the same question: how do you say the plural of a number (used as noun)?
Let me elaborate:
Suppose I'm explaining to a child how to add (in Math). I'd say:

Four twos make an eight.

Or I could say:

Four two's make an eight.

On one webpage I found the first one to be correct. I asked to an online tutor about this and she told me the second one is correct. So, which one is correct? Is that a general rule? If the second one is correct, would that mean it applies to all numbers?

A: The first is correct:

Four twos make an eight.

It is good and right to say and write, "twos," in a situation like this, as with any number—following all the normal rules of adding "s" to make a noun plural... "fives", "twenties" (y -> i, +es), et cetera.
The apostrophe...

two's

...indicates a possessive, not a plural. That would be a different situation, such as if you were talking about the font the two was written in, "The two's serifs are larger in the Tex Gyre Schola font." Or, in Math, "The two's quotient can only be a one or a two if it is to be a whole number."

Links (Grammarly):

*

*Apostrophe Rules

*Plural Nouns: Rules and Examples

A: The reason you have found different answers is because this is a matter of style, not a rule, and different style guides will give different guidance.
For instance, here is what The Chicago Manual of Style (17th ed.), 6.116, says about the apostrophe:

The apostrophe has three main uses: to indicate the possessive case, to stand in for missing letters or numerals, and—in rare instances—to form the plural of certain expressions.

And in 7.15:

Capital letters used as words, numerals used as nouns, and abbreviations usually form the plural by adding s. To aid comprehension, lowercase letters form the plural with an apostrophe and an s (compare "two as in llama" with "two a's in llama").
the three Rs
x's and y's
the 1990s
IRAs
URLs

The Associated Press says the following about apostrophes beyond the simple posessive:

OMITTED LETTERS: I've, it's, don't, rock 'n' roll, 'tis the season to be jolly. He is a ne'er-do-well.
OMITTED FIGURES: The class of '62. The Spirit of '76. The '20s.
PLURALS OF A SINGLE LETTER: Mind your p's and q's. He learned the three R's and brought home a report card with four A's and two B's. The Oakland A's won the pennant.
DO NOT USE: For plurals of numerals or multiple-letter combinations.

Notice the conflicting guidance between the two when it comes to single capital letters.
However, according to both of these guides (which, together, are the most authoritative, in North America anyway), there would be no apostrophe for your number:

Four twos make an eight.

But you should follow whichever style guide you ascribe to.

Note, however, that this guidance has changed over time. About thirty years ago, it used to be that the apostrophe was used to make acronyms plural. We used to write DVD's, for example. That's something that most people no longer do.


text:
Q: Ray Tracer Uniform Grid Traversal in OpenCL I'm attempting to create a Real Time Ray Tracer using OpenCL however, I'm very new to OpenCL and how to use it.
As part of accelerating the ray tracing process, I have implemented a Uniform Grid which can be traversed via a form of the DDA algorithm seen here: http://www.cse.yorku.ca/~amana/research/grid.pdf
My problem is, although I can traverse the grid and grab the cells to check for objects, I am unable to actually access those objects (it sends the kernel build in to an endless loop). They exist in the array but I believe it is due to the way the GPU inlines the commands that it can't resolve the program.
The following is the piece of code that is having trouble, where 'grid' is a 4D array represented as a 1D (fourth dimension for holding each object in a cell), toAccess is the list of elements containing object IDs that were encountered during grid traversal, caughtObjs is the size of toAccess (amount of objects encountered) and objList is the list of object IDs I'm trying to get.
for(int i = 0; i < caughtObjs; i++){
     objList[i] = grid[toAccess[i]]; //Commenting out this line stops the build crash
}

So I'm assuming using an array to reference elements in another array is bad in OpenCL due to its inlining. So what is a common alternative used to combat this problem?
(Also, I'm aware you're meant to check one cell at a time but I'm not doing this because the depth of the loops required was killing OpenCL's build too.)


text:
Q: All links broken, Rails 4 I am using Rails 4.
I want to force visitor to choose his country. There are only two options Latvia and Estonia.
In main layout I have like this:

<%= link_to "Latvija", :country => :latvia %>

<%= link_to "Igaunija", :country => :estonia %>

In routes:
Rails.application.routes.draw do

 scope "(:country)", :locale => /latvia|estonia/ do

  resources :reports
   devise_for :admin_users, ActiveAdmin::Devise.config
  ActiveAdmin.routes(self)
 #get "/accept" => 'home#accept_and_redirect'

   scope "(:locale)", :locale => /lv|ee|ru/ do
     root 'home#index'

get 'advertisements/update_regions' => 'advertisements#update_regions', as: 'update_regions'

resources :reviews do
  member do
    put "like", to: "reviews#upvote"
    put "dislike", to: "reviews#downvote"
  end
end

    resources :advertisements do
         collection { post :search, to: 'advertisements#index' }
  member do
    put "like", to: "advertisements#upvote"
    put "dislike", to: "advertisements#downvote"
  end
end
   resources :services
    get "/help", to: "help#index"
  get "/rules", to: "rules#index"

 get "/blacklist", to: "blacklist#index"
  devise_for :users
    resources :users, only: [:show, :index] do
      member do
         put "like", to: "users#upvote"
         put "dislike", to: "users#downvote"

      end
    end
end
 end
end

What basically it does: It changes url to http://localhost:3000/latvia/lv/users/sign_up (works)
But when I go to http://localhost:3000/latvia/lv/advertisements it gives me error:
No route matches {:action=>"show", :controller=>"advertisements", :country=>#<Advertisement id: 82, name: "tij", region_id: 4, age: 19, height: 180, phone_number: "0202222", weight: 85,  email: "as@g.lv", description: "ahahi", created_at: "2014-11-28 14:39:12", updated_at: "2014-11-28 14:40:14", user_id: 14, country_id: 1, in_blacklist: false, admin_confirmed: false, vip: true, provaider: "few", your_ip: "wefwef">, :format=>nil, :id=>nil, :locale=>:lv} missing required keys: [:id]

So the links that is declared outside  scope "(:country)", :locale => /latvia|estonia/ do   end  works but those who inside don't.
What could cause this error ? Or it is other way to set country in link ?
Thanks

A: You're just building the expected parameters wrong - or not passing everything that is needed. Take a look:
No route matches {
  :action=>"show",
  :controller=>"advertisements",
  :country=>#<Advertisement id: 82,
    name: "tij",
    region_id: 4,
    age: 19,
    height: 180,
    phone_number: "0202222",
    weight: 85,
    email: "as@g.lv",
    description: "ahahi",
    created_at: "2014-11-28 14:39:12",
    updated_at: "2014-11-28 14:40:14",
    user_id: 14,
    country_id: 1,
    in_blacklist: false,
    admin_confirmed: false,
    vip: true,
    provaider: "few",
    your_ip: "wefwef">,
  :format=>nil,
  :id=>nil,
  :locale=>:lv
}

missing required keys: [:id]

It seems like :country is actually an instance of an Advertisement class - that doesn't really make sense to me, so that could be an error.  Probably your scope is messing with another parameter because they have the same name.
More importantly, since :id is nil, you need to pass an id to the linked_to call.  Like this:
link_to "Latvija", :country => :latvia, :id => <whatever you want this id to be>


text:
Q: DynamoDB alternatives in terms of pricing? (Only pay what you use) What are other cloud-based, serverless, managed databases that have a pricing system similar to DynamoDB? I'm specifically talking about the On-Demand mode of DynamoDB
By similar I mean, being able to pay per requests and per GB/Month or similar, instead of paying a fixed monthly fee, I understand this will mostly gear towards NoSQL databases but for me it doesn't matter the type of database.
Apart from DynamoDB, I have also found FaunaDB, but it lacks documentation and tools/integrations
It's important to note that I'm not considering pay per hour here, as that is irrelevant once you go to production.

A: All of these have a monthly storage cost, and so I will only mention the read/write costs for each product.
Amazon Aurora Serverless is a SQL database that is priced based on the amount of "Aurora capacity units" you use for reads and writes with per-second billing. The database "pauses" itself while not in use, and you don't pay for ACUs while the DB is paused. There is a minimum billed amount of 5 minutes every time it starts up.
Amazon Timestream (currently only in preview) is a NoSQL database that is specifically optimized for storing time-series data. Pricing is based on the size of the data that is written or read during a request.
Strictly speaking, Amazon S3 is not a database—it's an object store—but it has a per-request pricing model. You can use Amazon EMR (per-second billing, one minute minimum) or Amazon Athena (per request billing, based on the amount of data scanned) to query/analyze data that is stored in S3.
Azure CosmosDB is a NoSQL database and has a per-request pricing model. it turns out that you have to pay for hourly provisioning of the request units.
GCP Big Query is an Analytics Data Warehouse. It has two pricing models, including a "pay for only what you use" pricing model that based on the amount of data read or written.


text:
Q: Is an ASP.NET MVC 3 Controller's Edit Action vulnerable to hacking the primary key? This post ASP.NET MVC UpdateModel vulnerable to hacking? asked the same question, but none of the answers specifically addressed hacking of the primary key.
Given code like this in a Controller:
    [HttpPost]
    public ActionResult Edit(string accountNumber, FormCollection formValues)
    {
      ...
    }

What is preventing a malicious user from modifying the value of accountNumber in the POST and thereby updating a completely different record?

A: Nothing prevents this, just like nothing prevents somebody from making a request to http://example.com/users/edit/12345 (where 12345 is an account you don't have access to).  You as the application developer are responsible for verifying that the user making the current request is actually authorized to access the resource being requested.
The answer to your particular question is the same as the answer to the question you linked to.  The primary key isn't really special.  If the user shouldn't be able to modify some property of the model, use the [Bind] attribute to control what properties are allowed to be bound.  Even better - don't have disallowed properties on the model in the first place.  (If you really wanted to stick to the second pattern, you can't use ORMs for binding, but I always recommend that anyway when I do security audits of MVC codebases.)


text:
Q: How to solve IE10 issue for my code Here is my code through which i am not able to display content using IE10 while its displaying in all IE9,IE8,IE7
// Clear the Table Body before insert the rows

this.V_Profile = function(value) {

    var tbl = new NG_ConfTable();

    tbl.addCaptionRow("Profile Definition");

    tbl.addCaptionRow(this.V_ProfileDef(value));

    tbl.addCaptionRow(" ");

    tbl.addCaptionRow("Client Authentication");

    //tbl.addCaptionRow(new V_AuthSettings(value));

    tbl.addCaptionRow(new V_AuthSettings(value, {networkAuthChangeAction : this.viewClientAuthSetting}));

    tbl.addCaptionRow(" ");

    //var clientForm = Element.wrap(this.V_ClientAuth(value), "form", {"id" : "clientAuthSetting"});

    tbl.addCaptionRow("Authentication Settings");

    tbl.addCaptionRow(this.V_ClientAuth(value), "clientAuth");

    tbl.addCaptionRow(" ");

    tbl.addCaptionRow("Wireless QoS");

    tbl.addCaptionRow(this.V_Qos(value));

    var form = Element.wrap(tbl, "form", {"id" : value["#"]});

    formChangeAction(form, function(){

        buttonPanel.get("cancel").enable(true);

    });

    return form;

}.bind(this);

// Insert the Row Element

the above code working for all browser not in IE10 so i am adding the extra piece of code into that is that correct plz suggest me to work in IE10.

A: Could http://mottie.github.io/tablesorter/docs/example-update-all.html be useful? This works on ie8, I hope to have understand your needs.


text:
Q: back link but not use history how to make back a href but not use history back
i have try to write this
config.php
$config['base_url'] = 'http://'.$_SERVER['HTTP_HOST'].'/webapp/';

and at index.php
( i have no idea to replace :
 else{ die("wrong password back");

the final goal is
on index.php is form login
than if it's ok then next page.
if wrong then i want to create link back to http://localhost/webapp
not http://localhost/webapp/index.php or other history url

A: die("wrong password back");

A: This is what you want:
die("wrong password back");

Edit:
This will send you back to  http://localhost/webapp not http://localhost/webapp/index.php

A: There are some options to choose from, each has a downside
Base URL
You can use the base URL defined in config.php
die('wrong password back'); // repalce `"` with `'` to remove `\`; this a preference

This seems like the best option, however, the browser with request $config['base_url'] again. Unlike, back option which will go a step back (and leave all fields (inputs) as they were before submitting)
History API
 else{ die('wrong password back');

This may and may not work, based on some condition, for example, having a set of previous pages in the history.


text:
Q: How to print in webview to bluetooth printer? I made a web page using spring, and I have to print some page with PDA.
So I tried to using webView in android studio, and I can the web page in PDA.
But I cant find how to print in web view to bluetooth printer, and I've tried to paring between PDA and bluetooth printer. (the window.print fuction is not working in webView)
I just need to print button, but its so hard for me. And I tried to using printooth API but its not working.


text:
Q: what is the first line of git format-patch output? when running git format-patch, the intent is to create an email representation of the code you wrote. So far so good. I'm no email expert, but it seems to me that the first line of this format-patch output isn't in a standard email header format...

From de8d128fb520416e0b029c913b3a5ce900d0320c Mon Sep 17 00:00:00 2001
Message-Id:
From: Christopher Harvey
Date: Wed, 3 Apr 2013 10:17:52 -0400
Subject: [PATCH 0/3] *** SUBJECT HERE ***
To: Christopher Harvey

*** BLURB HERE ***

Christopher Harvey (3):
  commit 2
  commit 3
  commit 4

 data | 3 +++
 1 file changed, 3 insertions(+)

--
1.7.12.4

what is From de8d128fb520416e0b029c913b3a5ce900d0320c Mon Sep 17 00:00:00 2001? what is the date for? It looks arbitrary to me, and it also prevents me from piping it to sendmail. I have to manually remove that line each time I want to send a patch.
thanks.

A: The output is in mbox format.  You can easily strip the first line with:
git format-patch --stdout <range> | sed 1d

and then do as you please with the result.
Alternatively you can use git itself to send the email.  Try:
git send-mail --smtp-server=<your server> *.patch

See GIT Send-Mail Manpage for all the options.

A: From git help format-patch

DISCUSSION
         The patch produced by git format-patch is in UNIX mailbox format, with
         a fixed "magic" time stamp to indicate that the file is output from
         format-patch rather than a real mailbox, like so:
       From 8f72bad1baf19a53459661343e21d6491c3908d3 Mon Sep 17 00:00:00 2001
       From: Tony Luck <tony.luck@intel.com>
       Date: Tue, 13 Jul 2010 11:42:54 -0700
       Subject: [PATCH] =?UTF-8?q?> > [IA64]=20Put=20ia64=20config=20files=20on=20the=20?=
        =?UTF-8?q?Uwe=20Kleine-K=C3=B6nig=20diet?=
       MIME-Version: 1.0
       Content-Type: text/plain; charset=UTF-8
       Content-Transfer-Encoding: 8bit

A: Git 2.32 (Q2 2021) actually explains pieces of the format-patch output upfront before the rest of the documentation starts referring to them.
See commit 28e29ee (24 Mar 2021) by Junio C Hamano (gitster).
(Merged by Junio C Hamano -- gitster -- in commit 5c2f7ff, 30 Mar 2021)

format-patch: give an overview of what a "patch" message is

The text says something called a "patch" is prepared one for each commit, it is suitable for e-mail submission, and "am" is the command to use it, but does not say what the "patch" really is.
The description in the page also refers to the "three-dash" line, but it is unclear what it is, unless the reader is given a more detailed overview of what the "patch" is.
Add a brief paragraph to give an overview of what the output looks like.

git format-patch now includes in its man page:

Prepare each commit with its "patch" in
one "message" per commit, formatted to resemble a UNIX mailbox.

A "message" generated by the command consists of three parts:

*

*A brief metadata header that begins with From <commit>
with a fixed Mon Sep 17 00:00:00 2001 datestamp to help programs
like "file(1)" to recognize that the file is an output from this
command, fields that record the author identity, the author date,
and the title of the change (taken from the first paragraph of the
commit log message).

*The second and subsequent paragraphs of the commit log message.

*The "patch", which is the "diff -p --stat" output (see
git diff) between the commit and its parent.
The log message and the patch is separated by a line with a
three-dash line.

A: As an appendix to Fredrik's answer, here are some relevant comments by Junio Hamano:

"Mon Sep 17 00:00:00 2001" is just a fake random date to make the Unix-From line recognizable by common MUA and does not have anything to do with your commit objects. The real date is on Date: header.

I actually once tried to change it to git's birthday (Thu Apr 7 15:13:13 2005 -0700) and I recall that it turned out that some people's scripts (or perhaps MUA) were broken and cared what was before "7" ... on the Unix-From line and discarded that update.

The "From $SHA1 $magic_timestamp" line and other header lines are there to make it look like a mbox

Links: 1, 2, 3.

A: from wikipedia (https://en.wikipedia.org/wiki/September_17)
2001 – The New York Stock Exchange reopens for trading after the September 11 attacks, the longest closure since the Great Depression.
maybe just coincidence!


text:
Q: Creating a back button in ASP.NET I have an old application which has numerous webforms. On every aspx page there is a designated back button, which takes the user to the previous page. All the buttons have the javascript onclick event set to history.back().
On one of the aspx pages, the back button would not work at all. We decided to use a server side button that would accomplish the same thing. The onclick event of the button has the necessary code to take the user to previous page.
First I created the onclick event in the following way, but the back button did not work at all. When I went in the debug mode, I found that the prevPage variable was holding the current page URL instead of the previous page URL.
private void btnBack_Click(object sender, System.EventArgs e)
{
    string prevPage = Request.UrlReferrer.ToString();
    Response.Redirect(prevPage);
}

Then I changed the prevPage to a static variable and defined its value to be set inside the if(!IsPostBack) block. Now the back button worked correctly.
static string prevPage = string.Empty;
private void Page_Load(object sender, System.EventArgs e)
{
    if(!IsPostBack)
    {
        prevPage = Request.UrlReferrer.ToString();
    }
}

private void btnBack_Click()
{
    Response.Redirect(prevPage);
}

I did not understand why the first attempt wouldn't work and why second attempt would.
I have a feeling that this might explain if there is something else going on with this particular page that would also not let the history.back() or history.go(-1) work.
Can you please provide some insight into this?
Edit: I am using IE8.

A: The first attempt would not work because when you click the button the post back has already occurred, therefore the Referrer URL is the one coming from the button (The page you are on).
In my opinion I would not send a request to the server to push the page back a level, it's an unnecessary request when it could be achieved quicker on the client side.

A: Man, DO NOT use static variable to store previous URL. It will be shared among all sessions and if case when your page can be achieved from different places, users will be confused.
If you want to track last page, Session is your best friend.

A: JavaScript:window.history.go(-2);return false;

That is all you need, put that in a onclientclick or simply in an anchor tag. You need two clicks because the first click will take you to a confirm submission page.


text:
Q: Работа со стеком №2 Получив ответ на свой вопрос, я сел записывать решение. Но вот в этой части кода выскакивает ошибка: Value of type void is not allowed. Что неверно? Ошибка в 4 строке
stack <int> temp;
if (st1.empty())
    return;
int val = st1.pop();
int minidx = 0, maxidx = 0;
int minval = val, maxval = val;
temp.push(val);

A: Должно возвращаться значение типа int: if (st1.empty()) return <- вот тут. Лучше вызвать исключение, т.к. код ошибки можно проигнорировать.


text:
Q: i just want to get past 3 months transaction need help. i just want to get past 3 months transaction.
SELECT *
FROM transaction
WHERE TransactionDate >= GETDATE()-90

transactionDate is a INT type with this format YYYYMMDD (ex. 20160812)
i got this error

Arithmetic overflow error converting expression to data type datetime.

any help will do

A: You can't convert an int directly to a date.  However, you can convert a string in YYYYMMDD format.  So, try this:
WHERE cast(cast(TransactionDate as varchar(255)) as date) >= GETDATE() - 90

Alternatively, you could do all the conversion on the current date side:
WHERE TransactionDate >= CONVERT(INT, CONVERT(VARCHAR(255), GETDATE() - 90, 112))

The advantage of this method is that the engine can use an index on TransactionDate.
That said, the right way to store the column is as a DATE.  SQL Server has built-in date/time data types for a reason; there is a lot of direct support for them.  Use the capabilities of the database.


text:
Q: Which expression captures the following statement in predicate logic: "There are no more than two students who studied for the test." S(x) means x studied for the test.
∃x∃y∃z ( S(x)∧S(y)∧¬S(z) )
¬∃x∃y∃z ( S(x)∧S(y)∧S(z) )
∀x∀y∃z ( S(x)∧S(y)∧¬S(z) )
∀x∀y∀z ( S(x)∧S(y)∧¬S(z) )
¬∃x∃y∀z ( S(x)∧S(y)∧¬S(z) )

A: The second option is ALMOST correct. The reason why it is incorrect is that you also have to state EXPLICITLY in the predicate that x, y and z are all different from each other, as follows:
$\neg\exists x\exists y\exists z(x\not=y\land x\not=z \land y\not=z \land Px\land Py \land Pz)$
Equivalent to the above would also be a statement like:
$\forall x\forall y\forall z(x\not=y\land x\not=z \land y\not=z \implies \neg(Px\land Py \land Pz))$
Or:
$\forall x\forall y\forall z(Px\land Py \land Pz \implies x=y\lor x=z \lor y=z)$